Skip to content

Commit 3b74250

Browse files
fix(subblock-race-condition): check loading state correctly (#1141)
* fix(subblock-race-condition): check loading state correctly" ; * clean up * remove useless comments * fix date fallback
1 parent c68800c commit 3b74250

File tree

3 files changed

+36
-17
lines changed

3 files changed

+36
-17
lines changed

apps/sim/app/workspace/[workspaceId]/w/[workflowId]/workflow.tsx

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ import { useExecutionStore } from '@/stores/execution/store'
3939
import { useVariablesStore } from '@/stores/panel/variables/store'
4040
import { useGeneralStore } from '@/stores/settings/general/store'
4141
import { useWorkflowDiffStore } from '@/stores/workflow-diff/store'
42-
import { useWorkflowRegistry } from '@/stores/workflows/registry/store'
42+
import { hasWorkflowsInitiallyLoaded, useWorkflowRegistry } from '@/stores/workflows/registry/store'
4343
import { useWorkflowStore } from '@/stores/workflows/workflow/store'
4444

4545
const logger = createLogger('Workflow')
@@ -908,14 +908,21 @@ const WorkflowContent = React.memo(() => {
908908
const workflowIds = Object.keys(workflows)
909909
const currentId = params.workflowId as string
910910

911+
// Check if workflows have been initially loaded at least once
912+
// This prevents premature navigation decisions on page refresh
913+
if (!hasWorkflowsInitiallyLoaded()) {
914+
logger.info('Waiting for initial workflow load...')
915+
return
916+
}
917+
911918
// Wait for both initialization and workflow loading to complete
912919
if (isLoading) {
913920
logger.info('Workflows still loading, waiting...')
914921
return
915922
}
916923

917-
// If no workflows exist, redirect to workspace root to let server handle workflow creation
918-
if (workflowIds.length === 0 && !isLoading) {
924+
// If no workflows exist after loading, redirect to workspace root
925+
if (workflowIds.length === 0) {
919926
logger.info('No workflows found, redirecting to workspace root')
920927
router.replace(`/workspace/${workspaceId}/w`)
921928
return

apps/sim/stores/workflows/registry/store.ts

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,9 @@ async function fetchWorkflowsFromDB(workspaceId?: string): Promise<void> {
164164
error: null,
165165
})
166166

167+
// Mark that initial load has completed
168+
hasInitiallyLoaded = true
169+
167170
// Only set first workflow as active if no active workflow is set and we have workflows
168171
const currentState = useWorkflowRegistry.getState()
169172
if (!currentState.activeWorkflowId && Object.keys(registryWorkflows).length > 0) {
@@ -177,6 +180,11 @@ async function fetchWorkflowsFromDB(workspaceId?: string): Promise<void> {
177180
)
178181
} catch (error) {
179182
logger.error('Error fetching workflows from DB:', error)
183+
184+
// Mark that initial load has completed even on error
185+
// This prevents indefinite waiting for workflows that failed to load
186+
hasInitiallyLoaded = true
187+
180188
useWorkflowRegistry.setState({
181189
isLoading: false,
182190
error: `Failed to load workflows: ${error instanceof Error ? error.message : 'Unknown error'}`,
@@ -256,21 +264,28 @@ export function isWorkspaceInTransition(): boolean {
256264
return isWorkspaceTransitioning
257265
}
258266

267+
/**
268+
* Checks if workflows have been initially loaded
269+
* @returns True if the initial workflow load has completed at least once
270+
*/
271+
export function hasWorkflowsInitiallyLoaded(): boolean {
272+
return hasInitiallyLoaded
273+
}
274+
275+
// Track if initial load has happened to prevent premature navigation
276+
let hasInitiallyLoaded = false
277+
259278
export const useWorkflowRegistry = create<WorkflowRegistry>()(
260279
devtools(
261280
(set, get) => ({
262281
// Store state
263282
workflows: {},
264283
activeWorkflowId: null,
265-
isLoading: true,
284+
isLoading: false,
266285
error: null,
267-
// Initialize deployment statuses
268286
deploymentStatuses: {},
269287

270-
// Set loading state
271288
setLoading: (loading: boolean) => {
272-
// Remove the broken logic that prevents loading when workflows exist
273-
// This was causing race conditions during deletion and sync operations
274289
set({ isLoading: loading })
275290
},
276291

@@ -295,6 +310,9 @@ export const useWorkflowRegistry = create<WorkflowRegistry>()(
295310
try {
296311
logger.info(`Switching to workspace: ${workspaceId}`)
297312

313+
// Reset the initial load flag when switching workspaces
314+
hasInitiallyLoaded = false
315+
298316
// Clear current workspace state
299317
resetWorkflowStores()
300318

@@ -500,7 +518,6 @@ export const useWorkflowRegistry = create<WorkflowRegistry>()(
500518
})
501519
})
502520

503-
// Update subblock store for this workflow
504521
useSubBlockStore.setState((state) => ({
505522
workflowValues: {
506523
...state.workflowValues,
@@ -542,10 +559,6 @@ export const useWorkflowRegistry = create<WorkflowRegistry>()(
542559
)
543560
}
544561

545-
// Set the workflow state in the store
546-
useWorkflowStore.setState(workflowState)
547-
548-
// CRITICAL: Set deployment status in registry when switching to workflow
549562
if (workflowData?.isDeployed || workflowData?.deployedAt) {
550563
set((state) => ({
551564
deploymentStatuses: {
@@ -560,11 +573,10 @@ export const useWorkflowRegistry = create<WorkflowRegistry>()(
560573
}))
561574
}
562575

563-
// Update the active workflow ID
576+
useWorkflowStore.setState(workflowState)
577+
564578
set({ activeWorkflowId: id, error: null })
565579

566-
// Emit a global event to notify that the active workflow has changed
567-
// This allows the workflow component to join the socket room
568580
window.dispatchEvent(
569581
new CustomEvent('active-workflow-changed', {
570582
detail: { workflowId: id },

apps/sim/stores/workflows/workflow/store.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ const initialState = {
4646
isDeployed: false,
4747
isPublished: false,
4848
},
49-
timestamp: Date.now(),
49+
timestamp: 0,
5050
action: 'Initial state',
5151
subblockValues: {},
5252
},

0 commit comments

Comments
 (0)