1- import { useNavigate , type AnyRouter } from "@tanstack/react-router" ;
1+ import { useNavigate , useRouter , type AnyRouter } from "@tanstack/react-router" ;
22
33import { GUEST_PAGE_PATH } from "../../guestPage" ;
44import { withoutAssistantCitationHash } from "../../lib/assistantCitationNavigation" ;
@@ -20,6 +20,7 @@ const SHELL_LESS_PATHS = new Set(["/pair", "/connect", "/connect-agent", GUEST_P
2020
2121let mainAppHref : string | null = null ;
2222let appModalReturnHref : string | null = null ;
23+ let appModalReturnHistoryIndex : number | null = null ;
2324let appModalReturnThreadTarget : ThreadRouteTarget | null = null ;
2425
2526/** Remembers where Settings, Usage, and the utility pages lead back to. */
@@ -29,6 +30,9 @@ export function startMainAppLocationTracking(router: AnyRouter): () => void {
2930 if ( isAppModalPage ( pathname ) || SHELL_LESS_PATHS . has ( pathname ) ) return ;
3031 const href = withoutAssistantCitationHash ( router . state . location . href ) ;
3132 appModalReturnHref = href ;
33+ // Only an entry that is exactly the return location can be stepped back to.
34+ appModalReturnHistoryIndex =
35+ href === router . state . location . href ? router . state . location . state . __TSR_index : null ;
3236 appModalReturnThreadTarget = resolveThreadRouteTarget (
3337 router . state . matches . at ( - 1 ) ?. params ?? { } ,
3438 ) ;
@@ -51,5 +55,18 @@ export function useNavigateToMainApp() {
5155/** Leaves Settings or Usage for the page that opened it. */
5256export function useCloseAppModal ( ) {
5357 const navigate = useNavigate ( ) ;
54- return ( ) => navigate ( { href : appModalReturnHref ?? mainAppHref ?? "/" } ) ;
58+ const router = useRouter ( ) ;
59+ return ( ) => {
60+ const href = appModalReturnHref ?? mainAppHref ?? "/" ;
61+ const returnIndex = appModalReturnHistoryIndex ?? 0 ;
62+ const steps = router . state . location . state . __TSR_index - returnIndex ;
63+ if ( returnIndex === 0 || steps <= 0 ) return navigate ( { href } ) ;
64+ // Go back to the entry before the return page and push it again: only a push drops the
65+ // modal's entries from forward history, and reusing the old entry avoids a duplicate stop.
66+ const unsubscribe = router . history . subscribe ( ( ) => {
67+ unsubscribe ( ) ;
68+ void navigate ( { href } ) ;
69+ } ) ;
70+ router . history . go ( - ( steps + 1 ) ) ;
71+ } ;
5572}
0 commit comments