diff --git a/src/composables/auth/useAuthActions.test.ts b/src/composables/auth/useAuthActions.test.ts index ecf89d8cd33..118853572db 100644 --- a/src/composables/auth/useAuthActions.test.ts +++ b/src/composables/auth/useAuthActions.test.ts @@ -43,6 +43,7 @@ const mockBillingState = vi.hoisted(() => ({ canAccessSubscriptionFeatures: false })) const mockClearAllWorkflowStorage = vi.hoisted(() => vi.fn()) +const mockPrepareWorkflowLogoutTransition = vi.hoisted(() => vi.fn()) const knownAuthErrorCodes = new Set([ 'auth/invalid-credential', @@ -77,7 +78,8 @@ vi.mock('@/platform/updates/common/toastStore', () => ({ })) vi.mock('@/platform/workflow/persistence/base/storageIO', () => ({ - clearAllWorkflowStorage: mockClearAllWorkflowStorage + clearAllWorkflowStorage: mockClearAllWorkflowStorage, + prepareWorkflowLogoutTransition: mockPrepareWorkflowLogoutTransition })) vi.mock('@/platform/workflow/management/stores/workflowStore', () => ({ @@ -214,12 +216,14 @@ describe('useAuthActions.logout', () => { await logout() - expect(mockClearAllWorkflowStorage).toHaveBeenCalledExactlyOnceWith({ - blockWrites: true - }) + expect(mockPrepareWorkflowLogoutTransition).toHaveBeenCalledOnce() + expect(mockClearAllWorkflowStorage).toHaveBeenCalledExactlyOnceWith() expect(mockAuthStore.logout.mock.invocationCallOrder[0]).toBeLessThan( - mockClearAllWorkflowStorage.mock.invocationCallOrder[0] + mockPrepareWorkflowLogoutTransition.mock.invocationCallOrder[0] ) + expect( + mockPrepareWorkflowLogoutTransition.mock.invocationCallOrder[0] + ).toBeLessThan(mockClearAllWorkflowStorage.mock.invocationCallOrder[0]) expect( mockClearAllWorkflowStorage.mock.invocationCallOrder[0] ).toBeLessThan(navigationSpy.mock.invocationCallOrder[0]) @@ -231,6 +235,7 @@ describe('useAuthActions.logout', () => { await logout() + expect(mockPrepareWorkflowLogoutTransition).not.toHaveBeenCalled() expect(mockClearAllWorkflowStorage).not.toHaveBeenCalled() }) diff --git a/src/composables/auth/useAuthActions.ts b/src/composables/auth/useAuthActions.ts index 6eaf58a8414..b4729e1d2dd 100644 --- a/src/composables/auth/useAuthActions.ts +++ b/src/composables/auth/useAuthActions.ts @@ -10,7 +10,10 @@ import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' import type { AuthFlowAction } from '@/platform/telemetry/types' import { useToastStore } from '@/platform/updates/common/toastStore' -import { clearAllWorkflowStorage } from '@/platform/workflow/persistence/base/storageIO' +import { + clearAllWorkflowStorage, + prepareWorkflowLogoutTransition +} from '@/platform/workflow/persistence/base/storageIO' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { useDialogService } from '@/services/dialogService' @@ -113,7 +116,10 @@ export const useAuthActions = () => { } await authStore.logout() - if (isCloud) clearAllWorkflowStorage({ blockWrites: true }) + if (isCloud) { + prepareWorkflowLogoutTransition() + clearAllWorkflowStorage() + } toastStore.add({ severity: 'success', diff --git a/src/platform/workflow/persistence/base/storageIO.test.ts b/src/platform/workflow/persistence/base/storageIO.test.ts index cadd0a6511e..a4105d8e6f7 100644 --- a/src/platform/workflow/persistence/base/storageIO.test.ts +++ b/src/platform/workflow/persistence/base/storageIO.test.ts @@ -337,10 +337,11 @@ describe('storageIO', () => { expect(sessionStorage.getItem('unrelated')).toBe('keep') }) - it('blocks workflow writes after cleanup starts', async () => { + it('blocks workflow writes during logout cleanup', async () => { const isolatedStorageIO = await import('./storageIO') - isolatedStorageIO.clearAllWorkflowStorage({ blockWrites: true }) + isolatedStorageIO.prepareWorkflowLogoutTransition() + isolatedStorageIO.clearAllWorkflowStorage() expect(isolatedStorageIO.isStorageAvailable()).toBe(false) expect( @@ -387,7 +388,7 @@ describe('storageIO', () => { }) }) - describe('clearWorkflowRestoreState', () => { + describe('workflow storage transitions', () => { it('blocks writes and clears restore state when a persistence flush fails', async () => { const isolatedStorageIO = await import('./storageIO') localStorage.setItem('workflow', '{}') @@ -421,6 +422,98 @@ describe('storageIO', () => { consoleWarnSpy.mockRestore() }) + it('resumes writes when a workspace transition is cancelled', async () => { + const isolatedStorageIO = await import('./storageIO') + + const cancelTransition = + isolatedStorageIO.prepareWorkflowWorkspaceTransition() + expect( + isolatedStorageIO.writePayload('ws-1', 'blocked', { + data: '{}', + updatedAt: 1 + }) + ).toBe(false) + + cancelTransition() + + expect( + isolatedStorageIO.writePayload('ws-1', 'resumed', { + data: '{}', + updatedAt: 2 + }) + ).toBe(true) + }) + + it('preserves unavailable storage when a workspace transition is cancelled', async () => { + const isolatedStorageIO = await import('./storageIO') + + isolatedStorageIO.markStorageUnavailable() + const cancelTransition = + isolatedStorageIO.prepareWorkflowWorkspaceTransition() + cancelTransition() + + expect(isolatedStorageIO.isStorageAvailable()).toBe(false) + expect( + isolatedStorageIO.writePayload('ws-1', 'draft', { + data: '{}', + updatedAt: 1 + }) + ).toBe(false) + }) + + it('only resumes logout transitions after authentication recovers', async () => { + const isolatedStorageIO = await import('./storageIO') + + isolatedStorageIO.prepareWorkflowWorkspaceTransition() + isolatedStorageIO.completeWorkflowLogoutTransition() + expect(isolatedStorageIO.isStorageAvailable()).toBe(false) + + isolatedStorageIO.prepareWorkflowLogoutTransition() + isolatedStorageIO.completeWorkflowLogoutTransition() + + expect(isolatedStorageIO.isStorageAvailable()).toBe(true) + }) + + it('preserves unavailable storage after logout recovery', async () => { + const isolatedStorageIO = await import('./storageIO') + + isolatedStorageIO.markStorageUnavailable() + isolatedStorageIO.prepareWorkflowLogoutTransition() + isolatedStorageIO.completeWorkflowLogoutTransition() + + expect(isolatedStorageIO.isStorageAvailable()).toBe(false) + }) + + it('does not let a duplicate transition cancel the owner transition', async () => { + const isolatedStorageIO = await import('./storageIO') + + const cancelOwner = isolatedStorageIO.prepareWorkflowWorkspaceTransition() + const cancelDuplicate = + isolatedStorageIO.prepareWorkflowWorkspaceTransition() + cancelDuplicate() + expect(isolatedStorageIO.isStorageAvailable()).toBe(false) + + cancelOwner() + expect(isolatedStorageIO.isStorageAvailable()).toBe(true) + }) + + it('keeps reads available while a workspace transition blocks writes', async () => { + const isolatedStorageIO = await import('./storageIO') + + isolatedStorageIO.writePayload('ws-1', 'draft', { + data: '{}', + updatedAt: 1 + }) + const cancelTransition = + isolatedStorageIO.prepareWorkflowWorkspaceTransition() + + expect(isolatedStorageIO.readPayload('ws-1', 'draft')).not.toBeNull() + expect(isolatedStorageIO.getPayloadKeys('ws-1')).toContain('draft') + cancelTransition() + }) + }) + + describe('clearWorkflowRestoreState', () => { it('clears cross-workspace restore state without deleting scoped drafts', () => { localStorage.setItem('Comfy.Workflow.DraftIndex.v2:ws-1', '{}') localStorage.setItem('Comfy.Workflow.Draft.v2:ws-1:abc', '{}') diff --git a/src/platform/workflow/persistence/base/storageIO.ts b/src/platform/workflow/persistence/base/storageIO.ts index d0fb1b42a1d..48f6b9a350d 100644 --- a/src/platform/workflow/persistence/base/storageIO.ts +++ b/src/platform/workflow/persistence/base/storageIO.ts @@ -12,9 +12,25 @@ import type { } from './draftTypes' import { StorageKeys } from './storageKeys' -/** Flag indicating if storage is available */ -let storageAvailable = true -let workflowWritesBlocked = false +type StorageAvailability = 'available' | 'unavailable' +type WorkflowStorageState = + | { status: 'ready'; availability: StorageAvailability } + | { + status: 'transitioning' + reason: 'workspace' + resumeAvailability: StorageAvailability + ownerId: symbol + } + | { + status: 'transitioning' + reason: 'logout' + resumeAvailability: StorageAvailability + } + +let workflowStorageState: WorkflowStorageState = { + status: 'ready', + availability: 'available' +} const pendingPersistenceFlushes = new Set<() => void>() export function registerWorkflowPersistenceFlush( @@ -35,11 +51,23 @@ function flushPendingWorkflowPersistence(): void { } export function isStorageAvailable(): boolean { - return storageAvailable && !workflowWritesBlocked + return ( + workflowStorageState.status === 'ready' && + workflowStorageState.availability === 'available' + ) } export function markStorageUnavailable(): void { - storageAvailable = false + workflowStorageState = + workflowStorageState.status === 'transitioning' + ? { ...workflowStorageState, resumeAvailability: 'unavailable' } + : { status: 'ready', availability: 'unavailable' } +} + +function isStorageReadable(): boolean { + return workflowStorageState.status === 'transitioning' + ? workflowStorageState.resumeAvailability === 'available' + : workflowStorageState.availability === 'available' } function isQuotaExceeded(error: unknown): boolean { @@ -68,7 +96,7 @@ function isValidIndex(value: unknown): value is DraftIndexV2 { * Reads and parses the draft index from localStorage. */ export function readIndex(workspaceId: string): DraftIndexV2 | null { - if (!storageAvailable) return null + if (!isStorageReadable()) return null try { const key = StorageKeys.draftIndex(workspaceId) @@ -88,7 +116,7 @@ export function readIndex(workspaceId: string): DraftIndexV2 | null { * Writes the draft index to localStorage. */ export function writeIndex(workspaceId: string, index: DraftIndexV2): boolean { - if (!storageAvailable || workflowWritesBlocked) return false + if (!isStorageAvailable()) return false try { const key = StorageKeys.draftIndex(workspaceId) @@ -107,7 +135,7 @@ export function readPayload( workspaceId: string, draftKey: string ): DraftPayloadV2 | null { - if (!storageAvailable) return null + if (!isStorageReadable()) return null try { const key = `${StorageKeys.prefixes.draftPayload}${workspaceId}:${draftKey}` @@ -128,7 +156,7 @@ export function writePayload( draftKey: string, payload: DraftPayloadV2 ): boolean { - if (!storageAvailable || workflowWritesBlocked) return false + if (!isStorageAvailable()) return false try { const key = `${StorageKeys.prefixes.draftPayload}${workspaceId}:${draftKey}` @@ -165,7 +193,7 @@ export function deletePayloads(workspaceId: string, draftKeys: string[]): void { * Gets all draft payload keys for a workspace from localStorage. */ export function getPayloadKeys(workspaceId: string): string[] { - if (!storageAvailable) return [] + if (!isStorageReadable()) return [] const prefix = `${StorageKeys.prefixes.draftPayload}${workspaceId}:` const keys: string[] = [] @@ -394,7 +422,7 @@ function readLocalPointer( } function writeStorage(storage: Storage, key: string, value: string): void { - if (!storageAvailable || workflowWritesBlocked) return + if (!isStorageAvailable()) return try { storage.setItem(key, value) @@ -452,29 +480,65 @@ function removeStorageKeys( } } -export function clearWorkflowRestoreState( - options: { blockWrites?: boolean } = {} -): void { - if (options.blockWrites) { - prepareWorkflowWorkspaceTransition() - return - } - +export function clearWorkflowRestoreState(): void { removeStorageKeys(localStorage, legacyLocalRestoreKeys) removeStorageKeys(sessionStorage, sessionRestoreKeys, sessionRestorePrefixes) } -export function prepareWorkflowWorkspaceTransition(): void { - if (!workflowWritesBlocked) flushPendingWorkflowPersistence() - workflowWritesBlocked = true +export function prepareWorkflowWorkspaceTransition(): () => void { + let ownerId: symbol | undefined + if (workflowStorageState.status === 'ready') { + flushPendingWorkflowPersistence() + ownerId = Symbol('workflow-storage-transition') + workflowStorageState = { + status: 'transitioning', + reason: 'workspace', + resumeAvailability: workflowStorageState.availability, + ownerId + } + } clearWorkflowRestoreState() + + return () => { + if ( + workflowStorageState.status !== 'transitioning' || + workflowStorageState.reason !== 'workspace' || + workflowStorageState.ownerId !== ownerId + ) + return + + workflowStorageState = { + status: 'ready', + availability: workflowStorageState.resumeAvailability + } + } } -export function clearAllWorkflowStorage( - options: { blockWrites?: boolean } = {} -): void { - if (options.blockWrites) workflowWritesBlocked = true +export function prepareWorkflowLogoutTransition(): void { + workflowStorageState = { + status: 'transitioning', + reason: 'logout', + resumeAvailability: + workflowStorageState.status === 'transitioning' + ? workflowStorageState.resumeAvailability + : workflowStorageState.availability + } +} + +export function completeWorkflowLogoutTransition(): void { + if ( + workflowStorageState.status !== 'transitioning' || + workflowStorageState.reason !== 'logout' + ) + return + + workflowStorageState = { + status: 'ready', + availability: workflowStorageState.resumeAvailability + } +} +export function clearAllWorkflowStorage(): void { const localPrefixes = [ StorageKeys.prefixes.draftIndex, StorageKeys.prefixes.draftPayload, diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index b84d99a0b69..1d6f67d604d 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -1,11 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createApp, defineComponent, nextTick } from 'vue' +import { createApp, defineComponent, nextTick, reactive } from 'vue' import { createI18n } from 'vue-i18n' import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { StorageKeys } from '../base/storageKeys' -import { clearWorkflowRestoreState } from '../base/storageIO' +import * as storageIO from '../base/storageIO' import { useWorkflowDraftStoreV2 } from '../stores/workflowDraftStoreV2' import { useWorkflowPersistenceV2 } from './useWorkflowPersistenceV2' @@ -96,9 +96,15 @@ vi.mock('vue-router', () => ({ }) })) +const currentUserMocks = vi.hoisted(() => ({ + onUserLogout: vi.fn(), + onUserResolved: vi.fn() +})) + vi.mock('@/composables/auth/useCurrentUser', () => ({ useCurrentUser: () => ({ - onUserLogout: vi.fn() + onUserLogout: currentUserMocks.onUserLogout, + onUserResolved: currentUserMocks.onUserResolved }) })) @@ -128,8 +134,21 @@ vi.mock('@/platform/navigation/preservedQueryNamespaces', () => ({ PRESERVED_QUERY_NAMESPACES: { TEMPLATE: 'template', SHARE: 'share' } })) +const distributionMocks = vi.hoisted(() => ({ isCloud: false })) + vi.mock('@/platform/distribution/types', () => ({ - isCloud: true + get isCloud() { + return distributionMocks.isCloud + } +})) + +const teamWorkspaceStoreMocks = reactive({ + initState: 'uninitialized' as 'uninitialized' | 'ready' | 'error', + activeWorkspaceId: null as string | null +}) + +vi.mock('@/platform/workspace/stores/teamWorkspaceStore', () => ({ + useTeamWorkspaceStore: () => teamWorkspaceStoreMocks })) vi.mock('../migration/migrateV1toV2', () => ({ @@ -201,6 +220,9 @@ describe('useWorkflowPersistenceV2', () => { mocks.apiMock.removeEventListener.mockImplementation(() => {}) routeMocks.query = {} preservedQueryMocks.payloads = {} + distributionMocks.isCloud = false + teamWorkspaceStoreMocks.initState = 'uninitialized' + teamWorkspaceStoreMocks.activeWorkspaceId = null }) afterEach(() => { @@ -739,6 +761,7 @@ describe('useWorkflowPersistenceV2', () => { }) it('flushes the final source-workspace edit before blocking transition writes', async () => { + distributionMocks.isCloud = true const sourceWorkspaceId = 'workspace-a' const destinationWorkspaceId = 'workspace-b' sessionStorage.setItem( @@ -769,7 +792,7 @@ describe('useWorkflowPersistenceV2', () => { ) expect(localStorage.getItem(sourcePayloadKey)).toBeNull() - clearWorkflowRestoreState({ blockWrites: true }) + const cancelTransition = storageIO.prepareWorkflowWorkspaceTransition() sessionStorage.setItem( WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, JSON.stringify({ id: destinationWorkspaceId, type: 'team' }) @@ -793,5 +816,145 @@ describe('useWorkflowPersistenceV2', () => { expect( sessionStorage.getItem(StorageKeys.openPaths('test-client')) ).toBeNull() + cancelTransition() + }) + + it('resumes workflow writes once workspace readiness is confirmed after authentication recovers', async () => { + distributionMocks.isCloud = true + localStorage.setItem('Comfy.Workflow.DraftIndex.v2:workspace-a', '{}') + sessionStorage.setItem('Comfy.Workflow.ActivePath:test-client', '{}') + mountWorkflowPersistence() + + const onLogout = currentUserMocks.onUserLogout.mock.calls[0][0] + const onUserResolved = currentUserMocks.onUserResolved.mock.calls[0][0] + onLogout() + + expect(localStorage).toHaveLength(0) + expect(sessionStorage).toHaveLength(0) + expect( + storageIO.writePayload('workspace-a', 'blocked', { + data: '{}', + updatedAt: 1 + }) + ).toBe(false) + + onUserResolved({ id: 'user-a' }) + + expect( + storageIO.writePayload('workspace-a', 'still-blocked', { + data: '{}', + updatedAt: 2 + }) + ).toBe(false) + + teamWorkspaceStoreMocks.activeWorkspaceId = 'workspace-a' + teamWorkspaceStoreMocks.initState = 'ready' + await nextTick() + + expect( + storageIO.writePayload('workspace-a', 'resumed', { + data: '{}', + updatedAt: 3 + }) + ).toBe(true) + }) + + it('cancels stale workspace-readiness watchers across authentication episodes', async () => { + distributionMocks.isCloud = true + const completeTransitionSpy = vi.spyOn( + storageIO, + 'completeWorkflowLogoutTransition' + ) + mountWorkflowPersistence() + + const onLogout = currentUserMocks.onUserLogout.mock.calls[0][0] + const onUserResolved = currentUserMocks.onUserResolved.mock.calls[0][0] + onLogout() + onUserResolved({ id: 'user-b' }) + onLogout() + onUserResolved({ id: 'user-c' }) + + teamWorkspaceStoreMocks.activeWorkspaceId = 'workspace-c' + teamWorkspaceStoreMocks.initState = 'ready' + await nextTick() + + expect(completeTransitionSpy).toHaveBeenCalledOnce() + }) + + it('releases the write fence when workspace initialization fails permanently', async () => { + distributionMocks.isCloud = true + const completeTransitionSpy = vi.spyOn( + storageIO, + 'completeWorkflowLogoutTransition' + ) + mountWorkflowPersistence() + + const onLogout = currentUserMocks.onUserLogout.mock.calls[0][0] + const onUserResolved = currentUserMocks.onUserResolved.mock.calls[0][0] + onLogout() + onUserResolved({ id: 'user-a' }) + + expect(completeTransitionSpy).not.toHaveBeenCalled() + + teamWorkspaceStoreMocks.initState = 'error' + await nextTick() + + expect(completeTransitionSpy).toHaveBeenCalledOnce() + }) + + it('waits for workspace readiness and drops pending pre-logout edits', async () => { + distributionMocks.isCloud = true + const sourceWorkspaceId = 'workspace-a' + const destinationWorkspaceId = 'workspace-b' + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ id: sourceWorkspaceId, type: 'team' }) + ) + const workflowStore = useWorkflowStore() + const workflow = await workflowStore + .createTemporary('LogoutRecovery.json') + .load() + workflowStore.activeWorkflow = workflow + mountWorkflowPersistence() + mocks.state.currentGraph = { marker: 'stale-source-edit' } + mocks.state.graphChangedHandler?.() + + const onLogout = currentUserMocks.onUserLogout.mock.calls[0][0] + const onUserResolved = currentUserMocks.onUserResolved.mock.calls[0][0] + onLogout() + onUserResolved({ id: 'user-b' }) + await vi.runAllTimersAsync() + + const sourcePayloadKey = StorageKeys.draftPayload( + workflow.path, + sourceWorkspaceId + ) + const destinationPayloadKey = StorageKeys.draftPayload( + workflow.path, + destinationWorkspaceId + ) + const personalPayloadKey = StorageKeys.draftPayload( + workflow.path, + 'personal' + ) + expect(localStorage.getItem(sourcePayloadKey)).toBeNull() + expect(localStorage.getItem(destinationPayloadKey)).toBeNull() + expect(localStorage.getItem(personalPayloadKey)).toBeNull() + + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE, + JSON.stringify({ id: destinationWorkspaceId, type: 'team' }) + ) + teamWorkspaceStoreMocks.activeWorkspaceId = destinationWorkspaceId + teamWorkspaceStoreMocks.initState = 'ready' + await nextTick() + + mocks.state.currentGraph = { marker: 'destination-edit' } + mocks.state.graphChangedHandler?.() + await vi.runAllTimersAsync() + + expect(localStorage.getItem(sourcePayloadKey)).toBeNull() + expect(localStorage.getItem(personalPayloadKey)).toBeNull() + expect(localStorage.getItem(destinationPayloadKey)).not.toBeNull() }) }) diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts index a02f7f4bbb9..49397c676e9 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts @@ -10,7 +10,7 @@ import { debounce } from 'es-toolkit' import { useToast } from 'primevue' -import { tryOnScopeDispose } from '@vueuse/core' +import { tryOnScopeDispose, whenever } from '@vueuse/core' import { computed, nextTick, ref, watch } from 'vue' import { useI18n } from 'vue-i18n' import { useRoute, useRouter } from 'vue-router' @@ -23,6 +23,7 @@ import { import { PRESERVED_QUERY_NAMESPACES } from '@/platform/navigation/preservedQueryNamespaces' import { isCloud } from '@/platform/distribution/types' import { useSettingStore } from '@/platform/settings/settingStore' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import { ComfyWorkflow, @@ -32,6 +33,8 @@ import { PERSIST_DEBOUNCE_MS } from '../base/draftTypes' import type { StartupOutcome } from '../base/draftTypes' import { clearAllWorkflowStorage, + completeWorkflowLogoutTransition, + prepareWorkflowLogoutTransition, registerWorkflowPersistenceFlush } from '../base/storageIO' import { migrateV1toV2 } from '../migration/migrateV1toV2' @@ -55,18 +58,18 @@ export function useWorkflowPersistenceV2() { const draftStore = useWorkflowDraftStoreV2() const tabState = useWorkflowTabState() const toast = useToast() - const { onUserLogout } = useCurrentUser() + const { onUserLogout, onUserResolved } = useCurrentUser() + const teamWorkspaceStore = useTeamWorkspaceStore() + let stopWorkspaceReadinessWatcher: (() => void) | undefined + + function stopPendingWorkspaceReadinessWatcher(): void { + stopWorkspaceReadinessWatcher?.() + stopWorkspaceReadinessWatcher = undefined + } // Run migration on module load, passing clientId for tab state migration migrateV1toV2(undefined, api.clientId ?? api.initialClientId ?? undefined) - // Clear workflow persistence storage when user signs out (cloud only) - onUserLogout(() => { - if (isCloud) { - clearAllWorkflowStorage() - } - }) - const ensureTemplateQueryFromIntent = async () => { hydratePreservedQuery(TEMPLATE_NAMESPACE) const mergedQuery = mergePreservedQueryIntoQuery( @@ -144,6 +147,40 @@ export function useWorkflowPersistenceV2() { ) window.addEventListener('pagehide', flushPendingPersistence) + onUserLogout(() => { + if (!isCloud) return + stopPendingWorkspaceReadinessWatcher() + debouncedPersist.cancel() + prepareWorkflowLogoutTransition() + clearAllWorkflowStorage() + }) + onUserResolved(() => { + if (!isCloud) return + stopPendingWorkspaceReadinessWatcher() + + // Release the fence once initialization concludes either way: a resolved + // workspace, or a permanent init failure. Waiting on 'ready' alone would + // leave writes blocked for the rest of the session if init settles on + // 'error' (e.g. no workspaces available, retries exhausted). + const isWorkspaceInitConcluded = () => + (teamWorkspaceStore.initState === 'ready' && + teamWorkspaceStore.activeWorkspaceId !== null) || + teamWorkspaceStore.initState === 'error' + if (isWorkspaceInitConcluded()) { + completeWorkflowLogoutTransition() + return + } + + stopWorkspaceReadinessWatcher = whenever( + isWorkspaceInitConcluded, + () => { + stopWorkspaceReadinessWatcher = undefined + completeWorkflowLogoutTransition() + }, + { once: true } + ) + }) + const loadPreviousWorkflowFromStorage = async () => { const sessionPath = tabState.getActivePath() @@ -282,6 +319,7 @@ export function useWorkflowPersistenceV2() { window.removeEventListener('pagehide', flushPendingPersistence) unregisterPersistenceFlush() debouncedPersist.cancel() + stopPendingWorkspaceReadinessWatcher() }) // Restore workflow tabs states diff --git a/src/platform/workspace/stores/useWorkspaceAuth.test.ts b/src/platform/workspace/stores/useWorkspaceAuth.test.ts index 7d8fac15b61..4d03f20df99 100644 --- a/src/platform/workspace/stores/useWorkspaceAuth.test.ts +++ b/src/platform/workspace/stores/useWorkspaceAuth.test.ts @@ -1227,6 +1227,10 @@ describe('useWorkspaceAuthStore', () => { const store = useWorkspaceAuthStore() const { currentWorkspace, workspaceToken } = storeToRefs(store) let workspaceWhenRevocationHandled: string | null = null + const cancelWorkflowTransition = vi.fn() + mockPrepareWorkflowWorkspaceTransition.mockReturnValue( + cancelWorkflowTransition + ) mockForgetRevokedActiveWorkspace.mockImplementation(() => { workspaceWhenRevocationHandled = sessionStorage.getItem( WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE @@ -1249,6 +1253,8 @@ describe('useWorkspaceAuthStore', () => { expect(workspaceWhenRevocationHandled).toBe( JSON.stringify(mockWorkspaceWithRole) ) + expect(cancelWorkflowTransition).toHaveBeenCalledOnce() + expect(mockReload).not.toHaveBeenCalled() }) }) diff --git a/src/platform/workspace/stores/workspaceAuthStore.ts b/src/platform/workspace/stores/workspaceAuthStore.ts index 5d94cc3c7ca..e4d749c9eba 100644 --- a/src/platform/workspace/stores/workspaceAuthStore.ts +++ b/src/platform/workspace/stores/workspaceAuthStore.ts @@ -978,7 +978,8 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { function endWorkspaceSession(revokedWorkspaceId?: string): boolean { const hadContext = currentWorkspace.value !== null - if (isCloud && hadContext) prepareWorkflowWorkspaceTransition() + const cancelWorkflowTransition = + isCloud && hadContext ? prepareWorkflowWorkspaceTransition() : undefined const revokedWorkspaceHandled = revokedWorkspaceId ? useTeamWorkspaceStore().forgetRevokedActiveWorkspace(revokedWorkspaceId) : false @@ -988,7 +989,9 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { : hadContext if (isCloud && shouldReload) { window.location.reload() + return false } + cancelWorkflowTransition?.() return !isCloud && revokedWorkspaceHandled }