From 7b301c74a551f2073ce6c964806c5526b121a957 Mon Sep 17 00:00:00 2001 From: Mukhamediyar <86684638+myxamediyar@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:45:49 -0800 Subject: [PATCH 1/5] fix(workspaces): scope a departure's ownership scan to the workspaces it leaves Leaving a workspace takes its Project lock exclusively and then asks which workspaces the departing member owns shared resources in. That query scanned every row the member had ever created, in every workspace, and only the answer for the workspaces being left was used. For a member who has created a lot it takes tens of seconds, with the Project lock held throughout: a second departure or a file write in the same Project waits out the 5s lock timeout and fails with "Project is changing; retry the operation", and a retry that arrives after the slow departure commits is refused because the member has already left. Both ownership scans now take the ids the departure hands off (its workspaces, and their Projects), so the lookup reads only those rows. Callers that need every workspace or Project (account deletion, the departure preview, organization departure's Project pass) still scan unscoped. Co-Authored-By: Claude Opus 5.5 --- apps/sim/lib/projects/resource-handoff.ts | 21 +++++-- .../shared-resource-handoff.integration.ts | 59 ++++++++++++++++++- apps/sim/lib/workspaces/resource-handoff.ts | 36 +++++++---- 3 files changed, 98 insertions(+), 18 deletions(-) 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 ( From 33b436168231902e34c3684a460023d9f9777ed6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 3 Dec 2026 17:57:38 -0600 Subject: [PATCH 2/5] improvement(workspaces): leave a workspace and remove a teammate optimistically --- .../workspace-header/workspace-header.tsx | 9 +-- .../sidebar/hooks/use-workspace-management.ts | 21 +++--- .../w/components/sidebar/sidebar.tsx | 2 - apps/sim/hooks/queries/invitations.ts | 69 +++++++++++++++++-- 4 files changed, 76 insertions(+), 25 deletions(-) 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.ts b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/hooks/use-workspace-management.ts index 7fb992912d6..2c45fe12ab9 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,22 +204,22 @@ 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 + 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) throw error @@ -237,7 +237,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..1107fcee6cf 100644 --- a/apps/sim/hooks/queries/invitations.ts +++ b/apps/sim/hooks/queries/invitations.ts @@ -26,7 +26,12 @@ 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' @@ -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), @@ -394,8 +432,8 @@ type LeaveWorkspaceParams = ContractBodyInput { + await queryClient.cancelQueries({ queryKey: workspaceKeys.lists() }) + const previousLists = queryClient.getQueriesData({ + queryKey: workspaceKeys.lists(), + }) + queryClient.setQueriesData({ queryKey: workspaceKeys.lists() }, (old) => + old + ? { + ...old, + workspaces: old.workspaces.filter((ws) => ws.id !== workspaceId), + pinnedWorkspaceIds: old.pinnedWorkspaceIds.filter((id) => id !== workspaceId), + } + : old + ) + return { previousLists } + }, + onError: (_error, _variables, context) => { + for (const [queryKey, data] of context?.previousLists ?? []) { + queryClient.setQueryData(queryKey, data) + } + }, onSettled: (_data, _error, variables) => { queryClient.invalidateQueries({ queryKey: workspaceKeys.permissions(variables.workspaceId), From 6abfe2215561e97ca52db705769eaffc7aaee572 Mon Sep 17 00:00:00 2001 From: Mukhamediyar <86684638+myxamediyar@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:11:43 -0800 Subject: [PATCH 3/5] fix(workspaces): keep a left workspace out of the switcher while a list re-fetch races the leave Leaving the open workspace moves to the next one, and the visit that records re-fetches the workspace list. When that re-fetch reads the server before the leave commits, it overwrites the optimistic removal and the left workspace shows in the switcher again until the leave settles. useOrderedWorkspacesQuery now hides any workspace whose leave is pending, tracked through a leave mutation key. The leave removes the workspace from the lists again on success, and onSettled returns the list re-fetch, so the leave stays pending until the list is current. Co-Authored-By: Claude Opus 5.5 --- apps/sim/hooks/queries/invitations.ts | 34 ++++++++---- apps/sim/hooks/queries/workspace.test.tsx | 67 ++++++++++++++++++++++- apps/sim/hooks/queries/workspace.ts | 35 +++++++++++- 3 files changed, 123 insertions(+), 13 deletions(-) diff --git a/apps/sim/hooks/queries/invitations.ts b/apps/sim/hooks/queries/invitations.ts index 1107fcee6cf..ed18a32c8fb 100644 --- a/apps/sim/hooks/queries/invitations.ts +++ b/apps/sim/hooks/queries/invitations.ts @@ -36,7 +36,7 @@ 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, @@ -431,14 +431,29 @@ 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. 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 }, @@ -451,13 +466,7 @@ export function useLeaveWorkspace() { queryKey: workspaceKeys.lists(), }) queryClient.setQueriesData({ queryKey: workspaceKeys.lists() }, (old) => - old - ? { - ...old, - workspaces: old.workspaces.filter((ws) => ws.id !== workspaceId), - pinnedWorkspaceIds: old.pinnedWorkspaceIds.filter((id) => id !== workspaceId), - } - : old + withoutWorkspace(old, workspaceId) ) return { previousLists } }, @@ -466,16 +475,19 @@ export function useLeaveWorkspace() { 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, }) From e69cfbb85aeabd221614671fe4ea34e48e548a8a Mon Sep 17 00:00:00 2001 From: Mukhamediyar <86684638+myxamediyar@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:34:20 -0800 Subject: [PATCH 4/5] fix(workspaces): return the user to where they were when a leave is refused Leaving the open workspace moves to the next one before the server answers. When the server refuses the leave (the last admin, the billing account), the rollback restored the workspace list but left the user on the other workspace. A refusal now takes the user back to the path they left, unless they have moved on to another workspace since. It pushes that path directly: the navigation away may still be in flight, and the rollback makes the left workspace active again, so switchWorkspace would do nothing. Co-Authored-By: Claude Opus 5.5 --- .../use-workspace-management.dom.test.tsx | 131 ++++++++++++++++++ .../sidebar/hooks/use-workspace-management.ts | 16 ++- 2 files changed, 146 insertions(+), 1 deletion(-) create mode 100644 apps/sim/app/workspace/[workspaceId]/w/components/sidebar/hooks/use-workspace-management.dom.test.tsx 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..5643b255911 --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/hooks/use-workspace-management.dom.test.tsx @@ -0,0 +1,131 @@ +/** + * @vitest-environment jsdom + */ + +import { act } from 'react' +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 { sleep } from '@sim/utils/helpers' +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 Promise.resolve() + await sleep(1) + } + }) +} + +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 2c45fe12ab9..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 @@ -210,6 +210,7 @@ export function useWorkspaceManagement({ const nextWorkspace = isLeavingCurrentWorkspace ? workspacesRef.current.find((w) => w.id !== workspaceToLeave.id) : undefined + const returnHref = pathname try { const leave = leaveWorkspaceMutation.mutateAsync({ @@ -222,10 +223,23 @@ export function useWorkspaceManagement({ logger.info('Left workspace successfully:', workspaceToLeave.id) } 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 { From 00e9b7234126190c3543e1b04fdea01e52072ef8 Mon Sep 17 00:00:00 2001 From: Mukhamediyar <86684638+myxamediyar@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:47:31 -0800 Subject: [PATCH 5/5] test(workspaces): yield to the macrotask queue instead of sleeping in the leave hook test check:test-patterns refuses a new wall-clock wait in a unit test, and the refused-leave navigation test flushed React Query with sleep(1). It now yields with flushMacrotask, which is a zero-delay turn. Co-Authored-By: Claude Opus 5.5 --- .../sidebar/hooks/use-workspace-management.dom.test.tsx | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) 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 index 5643b255911..039ab8c5280 100644 --- 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 @@ -3,13 +3,13 @@ */ 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 { sleep } from '@sim/utils/helpers' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -52,10 +52,7 @@ function render(client: QueryClient, workspaceId: string) { async function flush() { await act(async () => { - for (let i = 0; i < 10; i++) { - await Promise.resolve() - await sleep(1) - } + for (let i = 0; i < 10; i++) await flushMacrotask() }) }