Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,6 @@ interface WorkspaceHeaderProps {
onUploadLogo: (workspaceId: string) => void
/** Callback to leave the workspace */
onLeaveWorkspace: (workspaceId: string) => Promise<void>
/** Whether workspace leave is in progress */
isLeavingWorkspace: boolean
/** Current user's session ID for owner check */
sessionUserId?: string
/** Whether the sidebar is collapsed */
Expand Down Expand Up @@ -144,7 +142,6 @@ function WorkspaceHeaderImpl({
isDeletingWorkspace,
onUploadLogo,
onLeaveWorkspace,
isLeavingWorkspace,
sessionUserId,
isCollapsed = false,
onExpandSidebar,
Expand Down Expand Up @@ -412,10 +409,10 @@ function WorkspaceHeaderImpl({
const handleLeaveWorkspace = async () => {
if (!leaveTarget) return

setIsLeaveModalOpen(false)
setLeaveTarget(null)
try {
await onLeaveWorkspace(leaveTarget.id)
setIsLeaveModalOpen(false)
setLeaveTarget(null)
} catch (error) {
logger.error('Error leaving workspace:', error)
/**
Expand Down Expand Up @@ -877,8 +874,6 @@ function WorkspaceHeaderImpl({
confirm={{
label: 'Leave workspace',
onClick: handleLeaveWorkspace,
pending: isLeavingWorkspace,
pendingLabel: 'Leaving...',
}}
/>
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/**
* @vitest-environment jsdom
*/

import { act } from 'react'
import { flushMacrotask } from '@sim/testing/helpers/async'
import {
apiClientRequestMock,
apiClientRequestMockFns,
} from '@sim/testing/mocks/api-client-request.mock'
import { nextNavigationMock, nextNavigationMockFns } from '@sim/testing/mocks/next-navigation.mock'
import { workflowRegistryStoreMock } from '@sim/testing/mocks/workflow-registry-store.mock'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

vi.mock('@/lib/api/client/request', () => apiClientRequestMock)
vi.mock('next/navigation', () => nextNavigationMock)
vi.mock('@/stores/workflows/registry/store', () => workflowRegistryStoreMock)

import { ApiClientError } from '@/lib/api/client/errors'
import { listWorkspacesContract } from '@/lib/api/contracts'
import { removeWorkspaceMemberContract } from '@/lib/api/contracts/invitations'
import { useWorkspaceManagement } from '@/app/workspace/[workspaceId]/w/components/sidebar/hooks/use-workspace-management'

const mockRequestJson = apiClientRequestMockFns.mockRequestJson
const push = nextNavigationMockFns.router.push
const LEFT_PATH = '/workspace/ws-a/w/flow-1'

const workspace = (id: string) => ({ id, name: id, ownerId: 'owner', permissions: 'write' })

let root: Root | undefined
let management: ReturnType<typeof useWorkspaceManagement> | undefined

function Probe({ workspaceId }: { workspaceId: string }) {
management = useWorkspaceManagement({ workspaceId, sessionUserId: 'me' })
return null
}

const queryClient = () =>
new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })

function render(client: QueryClient, workspaceId: string) {
act(() => {
root?.render(
<QueryClientProvider client={client}>
<Probe workspaceId={workspaceId} />
</QueryClientProvider>
)
})
}

async function flush() {
await act(async () => {
for (let i = 0; i < 10; i++) await flushMacrotask()
})
}

describe('leaving the open workspace', () => {
let refuseLeave: (error: unknown) => void = () => {}

beforeEach(() => {
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
mockRequestJson.mockReset()
nextNavigationMockFns.mockUsePathname.mockReturnValue(LEFT_PATH)
mockRequestJson.mockImplementation((contract) => {
if (contract === listWorkspacesContract) {
return Promise.resolve({
workspaces: ['ws-a', 'ws-b', 'ws-c'].map(workspace),
lastActiveWorkspaceId: 'ws-a',
pinnedWorkspaceIds: [],
creationPolicy: null,
})
}
if (contract === removeWorkspaceMemberContract) {
return new Promise((_resolve, reject) => {
refuseLeave = reject
})
}
return Promise.resolve({ success: true })
})
root = createRoot(document.createElement('div'))
})

afterEach(() => {
act(() => root?.unmount())
root = undefined
management = undefined
})

const refusal = () =>
new ApiClientError({ status: 400, message: 'Cannot remove the last admin', body: {} })

it('returns the user to where they were when the leave is refused', async () => {
const client = queryClient()
render(client, 'ws-a')
await flush()

let leaving: Promise<void> | undefined
act(() => {
leaving = management?.handleLeaveWorkspace(workspace('ws-a') as never)
})
await flush()
expect(push).toHaveBeenLastCalledWith('/workspace/ws-b')

render(client, 'ws-b')
refuseLeave(refusal())
await act(() => expect(leaving).rejects.toThrow('Cannot remove the last admin'))
expect(push).toHaveBeenLastCalledWith(LEFT_PATH)
})

it('leaves a user who has moved on to another workspace where they are', async () => {
const client = queryClient()
render(client, 'ws-a')
await flush()

let leaving: Promise<void> | undefined
act(() => {
leaving = management?.handleLeaveWorkspace(workspace('ws-a') as never)
})
await flush()

render(client, 'ws-c')
refuseLeave(refusal())
await act(() => expect(leaving).rejects.toThrow('Cannot remove the last admin'))
expect(push).not.toHaveBeenCalledWith(LEFT_PATH)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -204,28 +204,42 @@ export function useWorkspaceManagement({

logger.info('Leaving workspace:', workspaceToLeave.id)

const isLeavingCurrentWorkspace =
workspaceIdRef.current === workspaceToLeave.id ||
activeWorkspaceRef.current?.id === workspaceToLeave.id
const nextWorkspace = isLeavingCurrentWorkspace
? workspacesRef.current.find((w) => w.id !== workspaceToLeave.id)
: undefined
const returnHref = pathname

try {
await leaveWorkspaceMutation.mutateAsync({
const leave = leaveWorkspaceMutation.mutateAsync({
userId: sessionUserId,
workspaceId: workspaceToLeave.id,
})
if (nextWorkspace) await switchWorkspace(nextWorkspace)
Comment thread
myxamediyar marked this conversation as resolved.
Resolved
await leave

logger.info('Left workspace successfully:', workspaceToLeave.id)

const isLeavingCurrentWorkspace =
workspaceIdRef.current === workspaceToLeave.id ||
activeWorkspaceRef.current?.id === workspaceToLeave.id

if (isLeavingCurrentWorkspace) {
const nextWorkspace = workspacesRef.current.find((w) => w.id !== workspaceToLeave.id)
if (nextWorkspace) await switchWorkspace(nextWorkspace)
}
} catch (error) {
logger.error('Error leaving workspace:', error)
/**
* A refused leave returns the user to where they were, unless they have moved on
* since. It pushes the path itself: the navigation away may still be in flight, and
* the rollback makes the left workspace active again, so `switchWorkspace` would no-op.
*/
const currentId = workspaceIdRef.current
if (
nextWorkspace &&
(currentId === workspaceToLeave.id || currentId === nextWorkspace.id)
) {
switchToWorkspace(workspaceToLeave.id)
routerRef.current.push(returnHref)
}
throw error
}
},
[switchWorkspace, sessionUserId]
[switchWorkspace, switchToWorkspace, sessionUserId, pathname]
)

return {
Expand All @@ -237,7 +251,6 @@ export function useWorkspaceManagement({
isWorkspacesLoading,
isCreatingWorkspace: createWorkspaceMutation.isPending,
isDeletingWorkspace: deleteWorkspaceMutation.isPending,
isLeavingWorkspace: leaveWorkspaceMutation.isPending,
updateWorkspace,
switchWorkspace,
handleCreateWorkspace,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,6 @@ export const Sidebar = memo(function Sidebar({
handleCreateWorkspace,
isCreatingWorkspace,
isDeletingWorkspace,
isLeavingWorkspace,
updateWorkspace,
confirmDeleteWorkspace,
handleLeaveWorkspace,
Expand Down Expand Up @@ -1441,7 +1440,6 @@ export const Sidebar = memo(function Sidebar({
isDeletingWorkspace={isDeletingWorkspace}
onUploadLogo={handleUploadLogo}
onLeaveWorkspace={handleLeaveWorkspaceWrapper}
isLeavingWorkspace={isLeavingWorkspace}
sessionUserId={sessionData?.user?.id}
isCollapsed={isCollapsed}
onExpandSidebar={toggleCollapsed}
Expand Down
89 changes: 80 additions & 9 deletions apps/sim/hooks/queries/invitations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,17 @@ import {
removeWorkspaceMemberContract,
resendInvitationContract,
} from '@/lib/api/contracts/invitations'
import { updateWorkspacePermissionsContract } from '@/lib/api/contracts/workspaces'
import {
updateWorkspacePermissionsContract,
type WorkspaceMember,
type WorkspacePermissions,
type WorkspacesResponse,
} from '@/lib/api/contracts/workspaces'
import { organizationKeys } from '@/hooks/queries/organization'
import { refreshSessionQuery } from '@/hooks/queries/session'
import { workspaceCredentialKeys } from '@/hooks/queries/utils/credential-keys'
import { subscriptionKeys } from '@/hooks/queries/utils/subscription-keys'
import { workspaceKeys } from '@/hooks/queries/workspace'
import { LEAVE_WORKSPACE_MUTATION_KEY, workspaceKeys } from '@/hooks/queries/workspace'

export const invitationKeys = {
all: ['invitations'] as const,
Expand Down Expand Up @@ -357,8 +362,8 @@ type RemoveMemberParams = ContractBodyInput<typeof removeWorkspaceMemberContract
}

/**
* Removes a member from a workspace.
* Invalidates the workspace permissions cache on success.
* Removes a member from a workspace. The member drops out of the cached teammate and member
* lists at once and comes back only if the server refuses the removal.
*/
export function useRemoveWorkspaceMember() {
const queryClient = useQueryClient()
Expand All @@ -370,6 +375,39 @@ export function useRemoveWorkspaceMember() {
body: { workspaceId },
})
},
onMutate: async ({ userId, workspaceId }) => {
const permissionsKey = workspaceKeys.permissions(workspaceId)
const membersKey = workspaceKeys.members(workspaceId)
await Promise.all([
queryClient.cancelQueries({ queryKey: permissionsKey }),
queryClient.cancelQueries({ queryKey: membersKey }),
])
const previousPermissions = queryClient.getQueryData<WorkspacePermissions>(permissionsKey)
const previousMembers = queryClient.getQueryData<WorkspaceMember[]>(membersKey)
if (previousPermissions?.users.some((user) => user.userId === userId)) {
queryClient.setQueryData<WorkspacePermissions>(permissionsKey, {
...previousPermissions,
users: previousPermissions.users.filter((user) => user.userId !== userId),
total: previousPermissions.total - 1,
})
}
if (previousMembers) {
queryClient.setQueryData<WorkspaceMember[]>(
membersKey,
previousMembers.filter((member) => member.userId !== userId)
)
}
return { previousPermissions, previousMembers }
},
onError: (_error, { workspaceId }, context) => {
if (context?.previousPermissions)
queryClient.setQueryData(
workspaceKeys.permissions(workspaceId),
context.previousPermissions
)
if (context?.previousMembers)
queryClient.setQueryData(workspaceKeys.members(workspaceId), context.previousMembers)
},
onSettled: (_data, _error, variables) => {
queryClient.invalidateQueries({
queryKey: workspaceKeys.permissions(variables.workspaceId),
Expand All @@ -393,30 +431,63 @@ type LeaveWorkspaceParams = ContractBodyInput<typeof removeWorkspaceMemberContra
userId: string
}

function withoutWorkspace(list: WorkspacesResponse | undefined, workspaceId: string) {
if (!list?.workspaces.some((ws) => ws.id === workspaceId)) return list
return {
...list,
workspaces: list.workspaces.filter((ws) => ws.id !== workspaceId),
pinnedWorkspaceIds: list.pinnedWorkspaceIds.filter((id) => id !== workspaceId),
}
}

/**
* Allows the current user to leave a workspace.
* Invalidates both permissions and workspace list caches on success.
* Allows the current user to leave a workspace. The workspace drops out of every cached
* workspace list at once and comes back only if the server refuses the leave.
*
* Leaving the open workspace moves to the next one, and the visit that records re-fetches the
* list, which can land before the leave commits and carry the workspace back.
* `useOrderedWorkspacesQuery` hides it while the leave is pending, success removes it again,
* and the leave stays pending until its own list re-fetch has settled.
*/
export function useLeaveWorkspace() {
const queryClient = useQueryClient()

return useMutation({
mutationKey: LEAVE_WORKSPACE_MUTATION_KEY,
mutationFn: async ({ userId, workspaceId }: LeaveWorkspaceParams) => {
return requestJson(removeWorkspaceMemberContract, {
params: { id: userId },
body: { workspaceId },
})
},
onMutate: async ({ workspaceId }) => {
await queryClient.cancelQueries({ queryKey: workspaceKeys.lists() })
const previousLists = queryClient.getQueriesData<WorkspacesResponse>({
queryKey: workspaceKeys.lists(),
})
queryClient.setQueriesData<WorkspacesResponse>({ queryKey: workspaceKeys.lists() }, (old) =>
withoutWorkspace(old, workspaceId)
)
return { previousLists }
},
onError: (_error, _variables, context) => {
for (const [queryKey, data] of context?.previousLists ?? []) {
queryClient.setQueryData(queryKey, data)
}
},
onSuccess: (_data, { workspaceId }) => {
queryClient.setQueriesData<WorkspacesResponse>({ queryKey: workspaceKeys.lists() }, (old) =>
withoutWorkspace(old, workspaceId)
)
},
onSettled: (_data, _error, variables) => {
queryClient.invalidateQueries({
queryKey: workspaceKeys.permissions(variables.workspaceId),
})
queryClient.invalidateQueries({
queryKey: workspaceKeys.lists(),
})
queryClient.invalidateQueries({
queryKey: workspaceKeys.detail(variables.workspaceId),
})
return queryClient.invalidateQueries({ queryKey: workspaceKeys.lists() })
},
})
}
Expand Down
Loading
Loading