diff --git a/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/components/workspace-header/workspace-header.tsx b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/components/workspace-header/workspace-header.tsx index ad1a19055af..7c389239d86 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/components/workspace-header/workspace-header.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/components/workspace-header/workspace-header.tsx @@ -112,8 +112,6 @@ interface WorkspaceHeaderProps { onUploadLogo: (workspaceId: string) => void /** Callback to leave the workspace */ onLeaveWorkspace: (workspaceId: string) => Promise - /** Whether workspace leave is in progress */ - isLeavingWorkspace: boolean /** Current user's session ID for owner check */ sessionUserId?: string /** Whether the sidebar is collapsed */ @@ -144,7 +142,6 @@ function WorkspaceHeaderImpl({ isDeletingWorkspace, onUploadLogo, onLeaveWorkspace, - isLeavingWorkspace, sessionUserId, isCollapsed = false, onExpandSidebar, @@ -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) /** @@ -877,8 +874,6 @@ function WorkspaceHeaderImpl({ confirm={{ label: 'Leave workspace', onClick: handleLeaveWorkspace, - pending: isLeavingWorkspace, - pendingLabel: 'Leaving...', }} /> diff --git a/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/hooks/use-workspace-management.dom.test.tsx b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/hooks/use-workspace-management.dom.test.tsx new file mode 100644 index 00000000000..039ab8c5280 --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/hooks/use-workspace-management.dom.test.tsx @@ -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 | 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( + + + + ) + }) +} + +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 | 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 | 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) + }) +}) diff --git a/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/hooks/use-workspace-management.ts b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/hooks/use-workspace-management.ts index 7fb992912d6..84a3d0ed1f8 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/hooks/use-workspace-management.ts +++ b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/hooks/use-workspace-management.ts @@ -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) + 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 { @@ -237,7 +251,6 @@ export function useWorkspaceManagement({ isWorkspacesLoading, isCreatingWorkspace: createWorkspaceMutation.isPending, isDeletingWorkspace: deleteWorkspaceMutation.isPending, - isLeavingWorkspace: leaveWorkspaceMutation.isPending, updateWorkspace, switchWorkspace, handleCreateWorkspace, diff --git a/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/sidebar.tsx b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/sidebar.tsx index e4027e40a73..a09099607db 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/sidebar.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/sidebar.tsx @@ -513,7 +513,6 @@ export const Sidebar = memo(function Sidebar({ handleCreateWorkspace, isCreatingWorkspace, isDeletingWorkspace, - isLeavingWorkspace, updateWorkspace, confirmDeleteWorkspace, handleLeaveWorkspace, @@ -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} diff --git a/apps/sim/hooks/queries/invitations.ts b/apps/sim/hooks/queries/invitations.ts index d1643cfd0e3..ed18a32c8fb 100644 --- a/apps/sim/hooks/queries/invitations.ts +++ b/apps/sim/hooks/queries/invitations.ts @@ -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, @@ -357,8 +362,8 @@ type RemoveMemberParams = ContractBodyInput { + 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(permissionsKey) + const previousMembers = queryClient.getQueryData(membersKey) + if (previousPermissions?.users.some((user) => user.userId === userId)) { + queryClient.setQueryData(permissionsKey, { + ...previousPermissions, + users: previousPermissions.users.filter((user) => user.userId !== userId), + total: previousPermissions.total - 1, + }) + } + if (previousMembers) { + queryClient.setQueryData( + 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), @@ -393,30 +431,63 @@ type LeaveWorkspaceParams = ContractBodyInput 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({ + queryKey: workspaceKeys.lists(), + }) + queryClient.setQueriesData({ 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({ 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() }) }, }) } diff --git a/apps/sim/hooks/queries/workspace.test.tsx b/apps/sim/hooks/queries/workspace.test.tsx index 23432c6e338..3f27c0fbe38 100644 --- a/apps/sim/hooks/queries/workspace.test.tsx +++ b/apps/sim/hooks/queries/workspace.test.tsx @@ -10,7 +10,7 @@ import { import { sleep } from '@sim/utils/helpers' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('@/lib/api/client/request', () => apiClientRequestMock) @@ -18,9 +18,12 @@ import { ApiClientError } from '@/lib/api/client/errors' import { createPinnedItemContract, deletePinnedItemContract, + listWorkspacesContract, recordWorkspaceVisitContract, } from '@/lib/api/contracts' +import { useLeaveWorkspace } from '@/hooks/queries/invitations' import { + useOrderedWorkspacesQuery, useRecordWorkspaceVisit, useToggleWorkspacePin, useWorkspacePermissionsQuery, @@ -195,6 +198,68 @@ describe('useToggleWorkspacePin', () => { }) }) +describe('leaving a workspace', () => { + const serverList = (ids: string[]) => ({ + workspaces: ids.map((id) => ({ id, name: id })), + lastActiveWorkspaceId: null, + pinnedWorkspaceIds: [], + creationPolicy: null, + }) + + function useSwitcher() { + return { listed: useOrderedWorkspacesQuery().data, leave: useLeaveWorkspace() } + } + + beforeEach(() => { + mockRequestJson.mockReset() + }) + + it('keeps the workspace out of the switcher when a list refetch lands before the leave commits', async () => { + let serverIds = ['ws-a', 'ws-b'] + let commitLeave: (value: { success: true }) => void = () => {} + mockRequestJson.mockImplementation((contract) => { + if (contract === listWorkspacesContract) return Promise.resolve(serverList(serverIds)) + return new Promise((resolve) => { + commitLeave = resolve + }) + }) + const { getResult, queryClient } = renderHookWithClient(useSwitcher) + const listedIds = () => getResult().listed?.map((ws) => ws.id) + await flush() + expect(listedIds()).toEqual(['ws-a', 'ws-b']) + + act(() => getResult().leave.mutate({ userId: 'me', workspaceId: 'ws-a' })) + await flush() + expect(listedIds()).toEqual(['ws-b']) + + /** Navigating away records a visit, whose settle refetches the list from the server. */ + await act(() => queryClient.invalidateQueries({ queryKey: workspaceKeys.lists() })) + await flush() + expect(listedIds()).toEqual(['ws-b']) + + serverIds = ['ws-b'] + commitLeave({ success: true }) + await flush() + expect(listedIds()).toEqual(['ws-b']) + expect(getResult().leave.isSuccess).toBe(true) + }) + + it('brings the workspace back when the leave is refused', async () => { + mockRequestJson.mockImplementation((contract) => + contract === listWorkspacesContract + ? Promise.resolve(serverList(['ws-a', 'ws-b'])) + : Promise.reject(apiError(400)) + ) + const { getResult } = renderHookWithClient(useSwitcher) + await flush() + + act(() => getResult().leave.mutate({ userId: 'me', workspaceId: 'ws-a' })) + await flush() + expect(getResult().leave.isError).toBe(true) + expect(getResult().listed?.map((ws) => ws.id)).toEqual(['ws-a', 'ws-b']) + }) +}) + describe('useRecordWorkspaceVisit', () => { function seedWorkspaces(queryClient: QueryClient, ids: string[]) { queryClient.setQueryData(workspaceKeys.list('active'), { diff --git a/apps/sim/hooks/queries/workspace.ts b/apps/sim/hooks/queries/workspace.ts index 33328bb6919..2aaae0d859e 100644 --- a/apps/sim/hooks/queries/workspace.ts +++ b/apps/sim/hooks/queries/workspace.ts @@ -1,8 +1,10 @@ +import { useCallback, useMemo } from 'react' import type { QueryClient } from '@tanstack/react-query' import { keepPreviousData, queryOptions, useMutation, + useMutationState, useQuery, useQueryClient, } from '@tanstack/react-query' @@ -134,12 +136,43 @@ export function usePinnedWorkspaceIds(enabled = true) { }) } +/** Identifies leaves in the mutation cache, so a workspace stays hidden while its leave is in flight. */ +export const LEAVE_WORKSPACE_MUTATION_KEY = ['workspace', 'leave'] as const + +function leavingWorkspaceId(variables: unknown): string | undefined { + if (typeof variables !== 'object' || variables === null || !('workspaceId' in variables)) { + return undefined + } + return typeof variables.workspaceId === 'string' ? variables.workspaceId : undefined +} + +/** + * Workspaces whose leave is still in flight. A list re-fetch that lands before the leave commits + * still carries them, so they are hidden by the pending mutation rather than only by editing the + * cached list, which such a re-fetch overwrites. + */ +function useLeavingWorkspaceIds(): ReadonlySet { + const ids = useMutationState({ + filters: { mutationKey: LEAVE_WORKSPACE_MUTATION_KEY, status: 'pending' }, + select: (mutation) => leavingWorkspaceId(mutation.state.variables), + }) + return useMemo(() => new Set(ids.filter((id): id is string => Boolean(id))), [ids]) +} + /** The viewer's active workspaces in switcher order: pinned, then most recently visited. */ export function useOrderedWorkspacesQuery(enabled = true) { + const leaving = useLeavingWorkspaceIds() + const select = useCallback( + (data: WorkspacesResponse) => { + const ordered = selectOrderedWorkspaces(data) + return leaving.size ? ordered.filter((ws) => !leaving.has(ws.id)) : ordered + }, + [leaving] + ) return useQuery({ queryKey: workspaceKeys.list('active'), queryFn: ({ signal }) => fetchWorkspaces('active', signal), - select: selectOrderedWorkspaces, + select, enabled, staleTime: WORKSPACE_LIST_STALE_TIME, }) diff --git a/apps/sim/lib/projects/resource-handoff.ts b/apps/sim/lib/projects/resource-handoff.ts index a279aa9aa38..3256be9d519 100644 --- a/apps/sim/lib/projects/resource-handoff.ts +++ b/apps/sim/lib/projects/resource-handoff.ts @@ -10,6 +10,7 @@ import { import { ORG_ADMIN_ROLES } from '@sim/platform-authz/workspace' import { and, asc, eq, inArray, ne, sql } from 'drizzle-orm' import { changeProjectStoragePayersInTx } from '@/lib/billing/storage/payer-transfer' +import { textArrayLiteral } from '@/lib/db/arrays' import type { DbOrTx, DbTransaction } from '@/lib/db/types' import { ProjectConflictError } from '@/lib/projects/errors' import { lockProjectBackfillWrites, lockProjects, tryLockProjects } from '@/lib/projects/membership' @@ -74,12 +75,22 @@ export async function findProjectSuccessor( return held.length === survivorIds.length ? teammate.userId : null } -/** Includes archived files and prior departures even when no environment grant remains. */ -export async function listSharedResourceProjectIdsForUser(executor: DbOrTx, userId: string) { +/** + * Includes archived files and prior departures even when no environment grant remains. + * `projectIds` limits the scan to those Projects, as a departure only asks about the ones it + * leaves. + */ +export async function listSharedResourceProjectIdsForUser( + executor: DbOrTx, + userId: string, + projectIds?: readonly string[] +) { + if (projectIds?.length === 0) return [] + const within = projectIds ? sql` AND project_id = ANY(${textArrayLiteral(projectIds)})` : sql`` const rows = await executor.execute<{ projectId: string }>(sql` SELECT DISTINCT project_id AS "projectId" FROM ( - SELECT project_id FROM workspace_files WHERE user_id = ${userId} AND project_id IS NOT NULL - UNION ALL SELECT project_id FROM folder WHERE user_id = ${userId} AND project_id IS NOT NULL + SELECT project_id FROM workspace_files WHERE user_id = ${userId} AND project_id IS NOT NULL${within} + UNION ALL SELECT project_id FROM folder WHERE user_id = ${userId} AND project_id IS NOT NULL${within} ) owned ORDER BY project_id `) return rows.map((row) => row.projectId) @@ -163,7 +174,7 @@ export async function handoffProjectsForWorkspaceDepartureTx( workspaceIds: string[] ) { const ids = await lockProjectsForResourceDepartureTx(tx, workspaceIds) - const owned = new Set(await listSharedResourceProjectIdsForUser(tx, departingUserId)) + const owned = new Set(await listSharedResourceProjectIdsForUser(tx, departingUserId, ids)) const affectedIds = ids.filter((id) => owned.has(id)) if (!affectedIds.length) return const records = await tx diff --git a/apps/sim/lib/workspaces/access/shared-resource-handoff.integration.ts b/apps/sim/lib/workspaces/access/shared-resource-handoff.integration.ts index 26f117eaaa6..7a4437431a8 100644 --- a/apps/sim/lib/workspaces/access/shared-resource-handoff.integration.ts +++ b/apps/sim/lib/workspaces/access/shared-resource-handoff.integration.ts @@ -33,11 +33,15 @@ import { generateId } from '@sim/utils/id' import { and, eq, inArray, sql } from 'drizzle-orm' import { afterAll, describe, expect, it } from 'vitest' import { removeUserFromOrganization } from '@/lib/billing/organizations/membership' -import { lockProjectsForResourceDepartureTx } from '@/lib/projects/resource-handoff' +import { + listSharedResourceProjectIdsForUser, + lockProjectsForResourceDepartureTx, +} from '@/lib/projects/resource-handoff' import { deleteUserAccount, getAccountDeletionPlan } from '@/lib/users/account-deletion' import { buildNewWorkflowRow } from '@/lib/workflows/persistence/new-workflow-row' import { revokeWorkspaceAccessTx } from '@/lib/workspaces/access/workspace-access' import { detachOrganizationWorkspacesTx } from '@/lib/workspaces/organization-workspaces' +import { listSharedResourceWorkspaceIdsForUser } from '@/lib/workspaces/resource-handoff' readTestDatabaseUrl() @@ -519,6 +523,59 @@ describe('shared resource retention across workspace departure and account erasu await assertTransferred(fixture) }) + it('scopes a departure’s ownership scan to the workspaces and Projects it leaves', async () => { + const fixture = await seedResources(false) + const elsewhereId = generateId() + workspaceIds.push(elsewhereId) + const [elsewhere] = await insertWorkspaceFixture(db, { + id: elsewhereId, + name: 'Elsewhere fixture', + ownerId: fixture.ownerId, + billedAccountUserId: fixture.ownerId, + }) + const elsewhereFolderId = generateId() + const projectFolders = [fixture.projectId, elsewhere.projectId].map((projectId) => ({ + id: generateId(), + resourceType: 'file' as const, + name: 'Project folder', + userId: fixture.departingId, + projectId, + })) + projectFolderIds.push(...projectFolders.map((row) => row.id)) + await db.insert(folder).values([ + { + id: elsewhereFolderId, + resourceType: 'workflow', + name: 'Elsewhere folder', + userId: fixture.departingId, + workspaceId: elsewhereId, + }, + ...projectFolders, + ]) + + expect(await listSharedResourceWorkspaceIdsForUser(db, fixture.departingId)).toEqual( + [fixture.workspaceId, elsewhereId].sort() + ) + expect( + await listSharedResourceWorkspaceIdsForUser(db, fixture.departingId, [fixture.workspaceId]) + ).toEqual([fixture.workspaceId]) + expect(await listSharedResourceWorkspaceIdsForUser(db, fixture.departingId, [])).toEqual([]) + expect( + await listSharedResourceProjectIdsForUser(db, fixture.departingId, [fixture.projectId]) + ).toEqual([fixture.projectId]) + + const result = await db.transaction((tx) => + revokeWorkspaceAccessTx(tx, { workspaceId: fixture.workspaceId, userId: fixture.departingId }) + ) + expect(result.revoked).toBe(true) + await assertTransferred(fixture) + const [left] = await db + .select({ userId: folder.userId }) + .from(folder) + .where(eq(folder.id, elsewhereFolderId)) + expect(left.userId).toBe(fixture.departingId) + }) + it('repairs references left by departures before the handoff fix', async () => { const fixture = await seedResources(true, false) await deleteUserAccount(fixture.departingId, { recordIdentity: false }) diff --git a/apps/sim/lib/workspaces/resource-handoff.ts b/apps/sim/lib/workspaces/resource-handoff.ts index 4b12ba56cc8..b2587f4e0af 100644 --- a/apps/sim/lib/workspaces/resource-handoff.ts +++ b/apps/sim/lib/workspaces/resource-handoff.ts @@ -13,7 +13,8 @@ import { workspaceFiles, } from '@sim/db/schema' import { ORG_ADMIN_ROLES } from '@sim/platform-authz/workspace' -import { and, asc, eq, inArray, isNull, sql } from 'drizzle-orm' +import { and, asc, type Column, eq, inArray, isNull, type SQL, sql } from 'drizzle-orm' +import { textArrayLiteral } from '@/lib/db/arrays' import type { DbOrTx, DbTransaction } from '@/lib/db/types' import { handoffProjectsForWorkspaceDepartureTx, @@ -26,20 +27,31 @@ import { reassignWorkflowOwnershipForWorkspaceMemberRemovalTx, } from '@/lib/workspaces/utils' -/** Finds surviving containers from ownership references, including departures predating handoff. */ -export async function listSharedResourceWorkspaceIdsForUser(executor: DbOrTx, userId: string) { +/** + * Finds surviving containers from ownership references, including departures predating handoff. + * `workspaceIds` limits the scan to those workspaces. A departure passes the ones it leaves: an + * unscoped scan reads every row the user ever created, under the departure's Project lock. + */ +export async function listSharedResourceWorkspaceIdsForUser( + executor: DbOrTx, + userId: string, + workspaceIds?: readonly string[] +) { + if (workspaceIds?.length === 0) return [] + const within = (column: Column): SQL => + workspaceIds ? sql` AND ${column} = ANY(${textArrayLiteral(workspaceIds)})` : sql`` const rows = await executor.execute<{ workspaceId: string }>(sql` SELECT DISTINCT "workspaceId" FROM ( - SELECT ${workflow.workspaceId} AS "workspaceId" FROM ${workflow} WHERE ${workflow.userId} = ${userId} - UNION ALL SELECT ${folder.workspaceId} FROM ${folder} WHERE ${folder.userId} = ${userId} - UNION ALL SELECT ${userTableDefinitions.workspaceId} FROM ${userTableDefinitions} WHERE ${userTableDefinitions.createdBy} = ${userId} - UNION ALL SELECT ${knowledgeBase.workspaceId} FROM ${knowledgeBase} WHERE ${knowledgeBase.userId} = ${userId} + SELECT ${workflow.workspaceId} AS "workspaceId" FROM ${workflow} WHERE ${workflow.userId} = ${userId}${within(workflow.workspaceId)} + UNION ALL SELECT ${folder.workspaceId} FROM ${folder} WHERE ${folder.userId} = ${userId}${within(folder.workspaceId)} + UNION ALL SELECT ${userTableDefinitions.workspaceId} FROM ${userTableDefinitions} WHERE ${userTableDefinitions.createdBy} = ${userId}${within(userTableDefinitions.workspaceId)} + UNION ALL SELECT ${knowledgeBase.workspaceId} FROM ${knowledgeBase} WHERE ${knowledgeBase.userId} = ${userId}${within(knowledgeBase.workspaceId)} UNION ALL SELECT ${workspaceFiles.workspaceId} FROM ${workspaceFiles} - WHERE ${workspaceFiles.userId} = ${userId} AND ${inArray(workspaceFiles.context, WORKSPACE_SHARED_FILE_CONTEXTS)} AND ${workspaceFiles.chatId} IS NULL - UNION ALL SELECT ${workspaceFile.workspaceId} FROM ${workspaceFile} WHERE ${workspaceFile.uploadedBy} = ${userId} + WHERE ${workspaceFiles.userId} = ${userId} AND ${inArray(workspaceFiles.context, WORKSPACE_SHARED_FILE_CONTEXTS)} AND ${workspaceFiles.chatId} IS NULL${within(workspaceFiles.workspaceId)} + UNION ALL SELECT ${workspaceFile.workspaceId} FROM ${workspaceFile} WHERE ${workspaceFile.uploadedBy} = ${userId}${within(workspaceFile.workspaceId)} UNION ALL SELECT ${workflowMcpServer.workspaceId} FROM ${workflowMcpServer} - WHERE ${workflowMcpServer.createdBy} = ${userId} AND NOT ${workflowMcpServer.isPublic} - UNION ALL SELECT ${workflow.workspaceId} FROM ${chat} JOIN ${workflow} ON ${workflow.id} = ${chat.workflowId} WHERE ${chat.userId} = ${userId} + WHERE ${workflowMcpServer.createdBy} = ${userId} AND NOT ${workflowMcpServer.isPublic}${within(workflowMcpServer.workspaceId)} + UNION ALL SELECT ${workflow.workspaceId} FROM ${chat} JOIN ${workflow} ON ${workflow.id} = ${chat.workflowId} WHERE ${chat.userId} = ${userId}${within(workflow.workspaceId)} ) owned WHERE "workspaceId" IS NOT NULL ORDER BY "workspaceId" `) @@ -155,7 +167,7 @@ export async function reassignSharedResourceOwnershipForWorkspaceMemberRemovalTx .orderBy(asc(workspace.id)) .for('no key update') - const owned = new Set(await listSharedResourceWorkspaceIdsForUser(tx, departingUserId)) + const owned = new Set(await listSharedResourceWorkspaceIdsForUser(tx, departingUserId, ids)) const unresolved: string[] = [] for (const row of rows) { if (