11import { useCallback , useEffect , useMemo , useRef , useState } from 'react'
22import { createLogger } from '@sim/logger'
3- import { useRouter } from 'next/navigation'
3+ import { usePathname , useRouter } from 'next/navigation'
44import { requestJson } from '@/lib/api/client/request'
55import { updateUserSettingsContract } from '@/lib/api/contracts'
66import { WorkspaceRecencyStorage } from '@/lib/core/utils/browser-storage'
@@ -25,6 +25,33 @@ interface UseWorkspaceManagementProps {
2525 sessionUserId ?: string
2626}
2727
28+ interface ResolveWorkspaceSwitchHrefParams {
29+ pathname : string
30+ currentWorkspaceId : string
31+ targetWorkspaceId : string
32+ }
33+
34+ /**
35+ * Keeps the active settings section across workspace switches without carrying
36+ * workspace-scoped detail IDs into the destination workspace.
37+ */
38+ export function resolveWorkspaceSwitchHref ( {
39+ pathname,
40+ currentWorkspaceId,
41+ targetWorkspaceId,
42+ } : ResolveWorkspaceSwitchHrefParams ) : string {
43+ const targetWorkspaceHref = `/workspace/${ targetWorkspaceId } `
44+ const settingsPrefix = `/workspace/${ currentWorkspaceId } /settings/`
45+ if ( ! pathname . startsWith ( settingsPrefix ) ) return targetWorkspaceHref
46+
47+ const [ section ] = pathname . slice ( settingsPrefix . length ) . split ( '/' )
48+ if ( ! section ) {
49+ throw new Error ( `Settings pathname is missing a section: ${ pathname } ` )
50+ }
51+
52+ return `${ targetWorkspaceHref } /settings/${ section } `
53+ }
54+
2855/**
2956 * Manages workspace operations including fetching, switching, creating, deleting, and leaving workspaces.
3057 * Handles URL synchronization and recency-based ordering. Route access is
@@ -40,6 +67,7 @@ export function useWorkspaceManagement({
4067 sessionUserId,
4168} : UseWorkspaceManagementProps ) {
4269 const router = useRouter ( )
70+ const pathname = usePathname ( )
4371 const switchToWorkspace = useWorkflowRegistry ( ( state ) => state . switchToWorkspace )
4472
4573 const { data : workspaces = [ ] , isLoading : isWorkspacesLoading } = useWorkspacesQuery (
@@ -157,15 +185,21 @@ export function useWorkspaceManagement({
157185 return
158186 }
159187
188+ const href = resolveWorkspaceSwitchHref ( {
189+ pathname,
190+ currentWorkspaceId : workspaceIdRef . current ,
191+ targetWorkspaceId : workspace . id ,
192+ } )
193+
160194 try {
161195 switchToWorkspace ( workspace . id )
162- routerRef . current ? .push ( `/workspace/ ${ workspace . id } ` )
196+ routerRef . current . push ( href )
163197 logger . info ( `Switched to workspace: ${ workspace . name } (${ workspace . id } )` )
164198 } catch ( error ) {
165199 logger . error ( 'Error switching workspace:' , error )
166200 }
167201 } ,
168- [ switchToWorkspace ]
202+ [ pathname , switchToWorkspace ]
169203 )
170204
171205 const handleCreateWorkspace = useCallback (
0 commit comments