-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathuse-collaborative-workflow.ts
More file actions
2217 lines (1946 loc) · 76.6 KB
/
Copy pathuse-collaborative-workflow.ts
File metadata and controls
2217 lines (1946 loc) · 76.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useCallback, useEffect, useRef } from 'react'
import { createLogger } from '@sim/logger'
import {
BLOCK_OPERATIONS,
BLOCKS_OPERATIONS,
EDGES_OPERATIONS,
OPERATION_TARGETS,
SUBBLOCK_OPERATIONS,
SUBFLOW_OPERATIONS,
VARIABLE_OPERATIONS,
WORKFLOW_OPERATIONS,
} from '@sim/realtime-protocol/constants'
import { generateId } from '@sim/utils/id'
import { useQueryClient } from '@tanstack/react-query'
import { isEqual } from 'es-toolkit'
import type { Edge } from 'reactflow'
import { useShallow } from 'zustand/react/shallow'
import { requestJson } from '@/lib/api/client/request'
import { getWorkflowStateContract } from '@/lib/api/contracts'
import { useSession } from '@/lib/auth/auth-client'
import {
type WorkflowSearchSubflowFieldId,
workflowSearchSubflowFieldMatchesExpected,
} from '@/lib/workflows/search-replace/subflow-fields'
import { useSocket } from '@/app/workspace/providers/socket-provider'
import { getBlock } from '@/blocks'
import { getSubBlocksDependingOnChange } from '@/blocks/utils'
import { normalizeName, RESERVED_BLOCK_NAMES } from '@/executor/constants'
import { invalidateDeploymentQueries } from '@/hooks/queries/deployments'
import { useUndoRedo } from '@/hooks/use-undo-redo'
import { useNotificationStore } from '@/stores/notifications'
import {
registerEmitFunctions,
useOperationQueue,
useOperationQueueStore,
} from '@/stores/operation-queue/store'
import { usePanelEditorStore } from '@/stores/panel'
import { useCodeUndoRedoStore, useUndoRedoStore } from '@/stores/undo-redo'
import { useVariablesStore } from '@/stores/variables/store'
import { useWorkflowDiffStore } from '@/stores/workflow-diff/store'
import {
applyWorkflowStateToStores,
WORKFLOW_DIFF_SETTLED_EVENT,
} from '@/stores/workflow-diff/utils'
import { useWorkflowRegistry } from '@/stores/workflows/registry/store'
import { useSubBlockStore } from '@/stores/workflows/subblock/store'
import { filterNewEdges, filterValidEdges, mergeSubblockState } from '@/stores/workflows/utils'
import { useWorkflowStore } from '@/stores/workflows/workflow/store'
import type {
BlockState,
Loop,
Parallel,
Position,
WorkflowState,
} from '@/stores/workflows/workflow/types'
import { findAllDescendantNodes, isBlockProtected } from '@/stores/workflows/workflow/utils'
const logger = createLogger('CollaborativeWorkflow')
export function useCollaborativeWorkflow() {
const queryClient = useQueryClient()
const undoRedo = useUndoRedo()
const isUndoRedoInProgress = useRef(false)
const lastDiffOperationId = useRef<string | null>(null)
useEffect(() => {
const moveHandler = (e: any) => {
const { blockId, before, after } = e.detail || {}
if (!blockId || !before || !after) return
if (isUndoRedoInProgress.current) return
undoRedo.recordBatchMoveBlocks([{ blockId, before, after }])
}
const parentUpdateHandler = (e: any) => {
const { blockId, oldParentId, newParentId, oldPosition, newPosition, affectedEdges } =
e.detail || {}
if (!blockId) return
if (isUndoRedoInProgress.current) return
undoRedo.recordUpdateParent(
blockId,
oldParentId,
newParentId,
oldPosition,
newPosition,
affectedEdges
)
}
const diffOperationHandler = (e: any) => {
const {
type,
baselineSnapshot,
proposedState,
diffAnalysis,
beforeAccept,
afterAccept,
beforeReject,
afterReject,
} = e.detail || {}
// Don't record during undo/redo operations
if (isUndoRedoInProgress.current) return
// Generate a unique ID for this diff operation to prevent duplicates
// Use block keys from the relevant states for each operation type
let stateForId
if (type === 'apply-diff') {
stateForId = proposedState
} else if (type === 'accept-diff') {
stateForId = afterAccept
} else if (type === 'reject-diff') {
stateForId = afterReject
}
const blockKeys = stateForId?.blocks ? Object.keys(stateForId.blocks).sort().join(',') : ''
const operationId = `${type}-${blockKeys}`
if (lastDiffOperationId.current === operationId) {
logger.debug('Skipping duplicate diff operation', { type, operationId })
return // Skip duplicate
}
lastDiffOperationId.current = operationId
if (type === 'apply-diff' && baselineSnapshot && proposedState) {
undoRedo.recordApplyDiff(baselineSnapshot, proposedState, diffAnalysis)
} else if (type === 'accept-diff' && beforeAccept && afterAccept) {
undoRedo.recordAcceptDiff(beforeAccept, afterAccept, diffAnalysis, baselineSnapshot)
} else if (type === 'reject-diff' && beforeReject && afterReject) {
undoRedo.recordRejectDiff(beforeReject, afterReject, diffAnalysis, baselineSnapshot)
}
}
window.addEventListener('workflow-record-move', moveHandler)
window.addEventListener('workflow-record-parent-update', parentUpdateHandler)
window.addEventListener('record-diff-operation', diffOperationHandler)
return () => {
window.removeEventListener('workflow-record-move', moveHandler)
window.removeEventListener('workflow-record-parent-update', parentUpdateHandler)
window.removeEventListener('record-diff-operation', diffOperationHandler)
}
}, [undoRedo])
const {
isConnected,
currentWorkflowId,
emitWorkflowOperation,
emitSubblockUpdate,
emitVariableUpdate,
onWorkflowOperation,
onSubblockUpdate,
onVariableUpdate,
onWorkflowDeleted,
onWorkflowReverted,
onWorkflowUpdated,
onWorkflowDeployed,
onOperationConfirmed,
onOperationFailed,
} = useSocket()
const activeWorkflowId = useWorkflowRegistry((state) => state.activeWorkflowId)
const { data: session } = useSession()
const { hasActiveDiff, isShowingDiff } = useWorkflowDiffStore(
useShallow((state) => ({
hasActiveDiff: state.hasActiveDiff,
isShowingDiff: state.isShowingDiff,
}))
)
const isBaselineDiffView = hasActiveDiff && !isShowingDiff
// Track if we're applying remote changes to avoid infinite loops
const isApplyingRemoteChange = useRef(false)
const reloadSequencesRef = useRef<Record<string, number>>({})
const {
addToQueue,
confirmOperation,
failOperation,
cancelOperationsForBlock,
cancelOperationsForVariable,
} = useOperationQueue()
// Register emit functions with operation queue store
useEffect(() => {
const registeredWorkflowId =
isConnected && currentWorkflowId === activeWorkflowId ? currentWorkflowId : null
registerEmitFunctions(
emitWorkflowOperation,
emitSubblockUpdate,
emitVariableUpdate,
registeredWorkflowId
)
}, [
activeWorkflowId,
currentWorkflowId,
emitWorkflowOperation,
emitSubblockUpdate,
emitVariableUpdate,
isConnected,
])
useEffect(() => {
const handleWorkflowOperation = (data: any) => {
const { operation, target, payload, userId, metadata } = data
if (isApplyingRemoteChange.current) return
// Filter broadcasts by workflowId to prevent cross-workflow updates
if (metadata?.workflowId && metadata.workflowId !== activeWorkflowId) {
logger.debug('Ignoring workflow operation for different workflow', {
broadcastWorkflowId: metadata.workflowId,
activeWorkflowId,
})
return
}
logger.info(`Received ${operation} on ${target} from user ${userId}`)
// Apply the operation to local state
isApplyingRemoteChange.current = true
try {
if (target === OPERATION_TARGETS.BLOCK) {
switch (operation) {
case BLOCK_OPERATIONS.UPDATE_NAME:
useWorkflowStore.getState().updateBlockName(payload.id, payload.name)
break
case BLOCK_OPERATIONS.UPDATE_ADVANCED_MODE:
useWorkflowStore.getState().setBlockAdvancedMode(payload.id, payload.advancedMode)
break
case BLOCK_OPERATIONS.UPDATE_CANONICAL_MODE:
useWorkflowStore
.getState()
.setBlockCanonicalMode(payload.id, payload.canonicalId, payload.canonicalMode)
break
}
} else if (target === OPERATION_TARGETS.BLOCKS) {
switch (operation) {
case BLOCKS_OPERATIONS.BATCH_UPDATE_POSITIONS: {
const { updates } = payload
if (Array.isArray(updates)) {
useWorkflowStore.getState().batchUpdatePositions(updates)
}
break
}
}
} else if (target === OPERATION_TARGETS.SUBBLOCK) {
switch (operation) {
case SUBBLOCK_OPERATIONS.BATCH_UPDATE: {
const { updates } = payload
if (Array.isArray(updates)) {
updates.forEach(
(update: { blockId: string; subblockId: string; value: unknown }) => {
useSubBlockStore
.getState()
.setValue(update.blockId, update.subblockId, update.value)
useWorkflowStore
.getState()
.syncDynamicHandleSubblockValue(
update.blockId,
update.subblockId,
update.value
)
}
)
}
break
}
}
} else if (target === OPERATION_TARGETS.EDGES) {
switch (operation) {
case EDGES_OPERATIONS.BATCH_REMOVE_EDGES: {
const { ids } = payload
if (Array.isArray(ids) && ids.length > 0) {
useWorkflowStore.getState().batchRemoveEdges(ids)
const updatedBlocks = useWorkflowStore.getState().blocks
const updatedEdges = useWorkflowStore.getState().edges
const graph = {
blocksById: updatedBlocks,
edgesById: Object.fromEntries(updatedEdges.map((e) => [e.id, e])),
}
const undoRedoStore = useUndoRedoStore.getState()
const stackKeys = Object.keys(undoRedoStore.stacks)
stackKeys.forEach((key) => {
const [wfId, uId] = key.split(':')
if (wfId === activeWorkflowId) {
undoRedoStore.pruneInvalidEntries(wfId, uId, graph)
}
})
}
break
}
case EDGES_OPERATIONS.BATCH_ADD_EDGES: {
const { edges } = payload
if (Array.isArray(edges) && edges.length > 0) {
const blocks = useWorkflowStore.getState().blocks
const currentEdges = useWorkflowStore.getState().edges
const validEdges = filterValidEdges(edges, blocks)
const newEdges = filterNewEdges(validEdges, currentEdges)
if (newEdges.length > 0) {
useWorkflowStore.getState().batchAddEdges(newEdges, { skipValidation: true })
}
}
break
}
}
} else if (target === OPERATION_TARGETS.SUBFLOW) {
switch (operation) {
case SUBFLOW_OPERATIONS.UPDATE:
// Handle subflow configuration updates (loop/parallel type changes, etc.)
if (payload.type === 'loop') {
const { config } = payload
if (config.loopType !== undefined) {
useWorkflowStore.getState().updateLoopType(payload.id, config.loopType)
}
if (config.iterations !== undefined) {
useWorkflowStore.getState().updateLoopCount(payload.id, config.iterations)
}
if (config.forEachItems !== undefined) {
useWorkflowStore.getState().setLoopForEachItems(payload.id, config.forEachItems)
}
if (config.whileCondition !== undefined) {
useWorkflowStore
.getState()
.setLoopWhileCondition(payload.id, config.whileCondition)
}
if (config.doWhileCondition !== undefined) {
useWorkflowStore
.getState()
.setLoopDoWhileCondition(payload.id, config.doWhileCondition)
}
} else if (payload.type === 'parallel') {
const { config } = payload
if (config.parallelType !== undefined) {
useWorkflowStore.getState().updateParallelType(payload.id, config.parallelType)
}
if (config.count !== undefined) {
useWorkflowStore.getState().updateParallelCount(payload.id, config.count)
}
if (config.batchSize !== undefined) {
useWorkflowStore.getState().updateParallelBatchSize(payload.id, config.batchSize)
}
if (config.distribution !== undefined) {
useWorkflowStore
.getState()
.updateParallelCollection(payload.id, config.distribution)
}
}
break
}
} else if (target === OPERATION_TARGETS.VARIABLE) {
switch (operation) {
case VARIABLE_OPERATIONS.ADD:
useVariablesStore.getState().addVariable(
{
workflowId: payload.workflowId,
name: payload.name,
type: payload.type,
value: payload.value,
},
payload.id
)
break
case VARIABLE_OPERATIONS.UPDATE:
if (payload.field === 'name') {
useVariablesStore
.getState()
.updateVariable(payload.variableId, { name: payload.value })
} else if (payload.field === 'value') {
useVariablesStore
.getState()
.updateVariable(payload.variableId, { value: payload.value })
} else if (payload.field === 'type') {
useVariablesStore
.getState()
.updateVariable(payload.variableId, { type: payload.value })
}
break
case VARIABLE_OPERATIONS.REMOVE:
useVariablesStore.getState().deleteVariable(payload.variableId)
break
}
} else if (target === OPERATION_TARGETS.WORKFLOW) {
switch (operation) {
case WORKFLOW_OPERATIONS.REPLACE_STATE:
if (payload.state) {
logger.info('Received workflow state replacement from remote user', {
userId,
blockCount: Object.keys(payload.state.blocks || {}).length,
edgeCount: (payload.state.edges || []).length,
hasActiveDiff,
isShowingDiff,
})
useWorkflowStore.getState().replaceWorkflowState(payload.state)
// Extract and apply subblock values
const subBlockValues: Record<string, Record<string, any>> = {}
Object.entries(payload.state.blocks || {}).forEach(
([blockId, block]: [string, any]) => {
subBlockValues[blockId] = {}
Object.entries(block.subBlocks || {}).forEach(
([subBlockId, subBlock]: [string, any]) => {
subBlockValues[blockId][subBlockId] = subBlock.value
}
)
}
)
if (activeWorkflowId) {
useSubBlockStore.getState().setWorkflowValues(activeWorkflowId, subBlockValues)
}
logger.info('Successfully applied remote workflow state replacement')
}
break
}
}
if (target === OPERATION_TARGETS.BLOCKS) {
switch (operation) {
case BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS: {
const { blocks, edges, subBlockValues: addedSubBlockValues } = payload
logger.info('Received batch-add-blocks from remote user', {
userId,
blockCount: (blocks || []).length,
edgeCount: (edges || []).length,
})
if (blocks && blocks.length > 0) {
useWorkflowStore
.getState()
.batchAddBlocks(blocks, edges || [], addedSubBlockValues || {})
}
logger.info('Successfully applied batch-add-blocks from remote user')
break
}
case BLOCKS_OPERATIONS.BATCH_REMOVE_BLOCKS: {
const { ids } = payload
logger.info('Received batch-remove-blocks from remote user', {
userId,
count: (ids || []).length,
})
if (ids && ids.length > 0) {
useWorkflowStore.getState().batchRemoveBlocks(ids)
}
logger.info('Successfully applied batch-remove-blocks from remote user')
break
}
case BLOCKS_OPERATIONS.BATCH_TOGGLE_ENABLED: {
const { blockIds } = payload
logger.info('Received batch-toggle-enabled from remote user', {
userId,
count: (blockIds || []).length,
})
if (blockIds && blockIds.length > 0) {
useWorkflowStore.getState().batchToggleEnabled(blockIds)
}
logger.info('Successfully applied batch-toggle-enabled from remote user')
break
}
case BLOCKS_OPERATIONS.BATCH_TOGGLE_HANDLES: {
const { blockIds } = payload
logger.info('Received batch-toggle-handles from remote user', {
userId,
count: (blockIds || []).length,
})
if (blockIds && blockIds.length > 0) {
useWorkflowStore.getState().batchToggleHandles(blockIds)
}
logger.info('Successfully applied batch-toggle-handles from remote user')
break
}
case BLOCKS_OPERATIONS.BATCH_TOGGLE_LOCKED: {
const { blockIds } = payload
logger.info('Received batch-toggle-locked from remote user', {
userId,
count: (blockIds || []).length,
})
if (blockIds && blockIds.length > 0) {
useWorkflowStore.getState().batchToggleLocked(blockIds)
}
logger.info('Successfully applied batch-toggle-locked from remote user')
break
}
case BLOCKS_OPERATIONS.BATCH_UPDATE_PARENT: {
const { updates } = payload
logger.info('Received batch-update-parent from remote user', {
userId,
count: (updates || []).length,
})
if (updates && updates.length > 0) {
useWorkflowStore.getState().batchUpdateBlocksWithParent(
updates.map(
(u: { id: string; parentId: string; position: { x: number; y: number } }) => ({
id: u.id,
position: u.position,
parentId: u.parentId || undefined,
})
)
)
}
logger.info('Successfully applied batch-update-parent from remote user')
break
}
}
}
} catch (error) {
logger.error('Error applying remote operation:', error)
} finally {
isApplyingRemoteChange.current = false
}
}
const handleSubblockUpdate = (data: any) => {
const { workflowId, blockId, subblockId, value, userId } = data
if (isApplyingRemoteChange.current) return
// Filter broadcasts by workflowId to prevent cross-workflow updates
if (workflowId && workflowId !== activeWorkflowId) {
logger.debug('Ignoring subblock update for different workflow', {
broadcastWorkflowId: workflowId,
activeWorkflowId,
})
return
}
logger.info(`Received subblock update from user ${userId}: ${blockId}.${subblockId}`)
isApplyingRemoteChange.current = true
try {
useSubBlockStore.getState().setValue(blockId, subblockId, value)
useWorkflowStore.getState().syncDynamicHandleSubblockValue(blockId, subblockId, value)
const blockType = useWorkflowStore.getState().blocks?.[blockId]?.type
if (activeWorkflowId && blockType === 'function' && subblockId === 'code') {
useCodeUndoRedoStore.getState().clear(activeWorkflowId, blockId, subblockId)
}
} catch (error) {
logger.error('Error applying remote subblock update:', error)
} finally {
isApplyingRemoteChange.current = false
}
}
const handleVariableUpdate = (data: any) => {
const { workflowId, variableId, field, value, userId } = data
if (isApplyingRemoteChange.current) return
// Filter broadcasts by workflowId to prevent cross-workflow updates
if (workflowId && workflowId !== activeWorkflowId) {
logger.debug('Ignoring variable update for different workflow', {
broadcastWorkflowId: workflowId,
activeWorkflowId,
})
return
}
logger.info(`Received variable update from user ${userId}: ${variableId}.${field}`)
isApplyingRemoteChange.current = true
try {
if (field === 'name') {
useVariablesStore.getState().updateVariable(variableId, { name: value })
} else if (field === 'value') {
useVariablesStore.getState().updateVariable(variableId, { value })
} else if (field === 'type') {
useVariablesStore.getState().updateVariable(variableId, { type: value })
}
} catch (error) {
logger.error('Error applying remote variable update:', error)
} finally {
isApplyingRemoteChange.current = false
}
}
const handleWorkflowDeleted = (data: any) => {
const { workflowId } = data
logger.warn(`Workflow ${workflowId} has been deleted`)
if (activeWorkflowId === workflowId) {
logger.info(
`Currently active workflow ${workflowId} was deleted, stopping collaborative operations`
)
const currentUserId = session?.user?.id || 'unknown'
useUndoRedoStore.getState().clear(workflowId, currentUserId)
isApplyingRemoteChange.current = false
}
}
const reloadWorkflowFromApi = async (workflowId: string, reason: string): Promise<boolean> => {
const reloadSequence = (reloadSequencesRef.current[workflowId] ?? 0) + 1
reloadSequencesRef.current[workflowId] = reloadSequence
const isLatestReload = () => reloadSequencesRef.current[workflowId] === reloadSequence
const pendingExternalUpdateAtStart =
useWorkflowDiffStore.getState().pendingExternalUpdates[workflowId] ?? 0
useWorkflowDiffStore.getState().setWorkflowReconciliationInProgress(workflowId, true)
const failLatestReconciliation = (message: string) => {
if (!isLatestReload()) return
const diffStore = useWorkflowDiffStore.getState()
if ((diffStore.pendingExternalUpdates[workflowId] ?? 0) <= pendingExternalUpdateAtStart) {
diffStore.clearExternalUpdatePending(workflowId)
}
diffStore.setWorkflowReconciliationInProgress(workflowId, false)
diffStore.setWorkflowReconciliationError(workflowId, message)
if ((useWorkflowDiffStore.getState().pendingExternalUpdates[workflowId] ?? 0) > 0) {
window.dispatchEvent(
new CustomEvent(WORKFLOW_DIFF_SETTLED_EVENT, { detail: { workflowId } })
)
}
}
// The contract's `state` is `workflowStateSchema` (loose at the wire
// level — `subBlocks.value` is `unknown`, optional flags omitted),
// but downstream consumers (replaceWorkflowState, the undo/redo
// graph) operate on the store's narrower `WorkflowState`. The
// server-of-record persists store-shaped values, so the runtime
// shape is the store type; we narrow once here at the trust
// boundary instead of sprinkling per-field casts.
let workflowState: WorkflowState | null = null
try {
const responseData = await requestJson(getWorkflowStateContract, {
params: { id: workflowId },
})
const wireState = responseData.data?.state
if (wireState) {
// double-cast-allowed: workflowStateSchema is structurally a supertype of the store's WorkflowState (subBlocks.value is `unknown`, optional booleans, etc.); the server persists store-shaped values so the runtime shape matches
workflowState = wireState as unknown as WorkflowState
if (Object.hasOwn(responseData.data, 'variables')) {
workflowState.variables = responseData.data.variables || {}
}
}
} catch (error) {
logger.error(`Failed to fetch workflow data after ${reason}`, { error })
failLatestReconciliation(
'Failed to sync the latest workflow changes. Refresh and try again.'
)
return false
}
if (!isLatestReload()) {
logger.debug(`Ignoring stale workflow reload after ${reason}`, { workflowId })
return false
}
if (!workflowState) {
logger.error(`No state found in workflow data after ${reason}`, { workflowId })
failLatestReconciliation('No workflow state was returned while syncing latest changes.')
return false
}
if (useWorkflowRegistry.getState().activeWorkflowId !== workflowId) {
logger.debug(`Ignoring workflow reload after active workflow changed`, { workflowId })
if (isLatestReload()) {
useWorkflowDiffStore.getState().setWorkflowReconciliationInProgress(workflowId, false)
}
return false
}
const diffStateBeforeApply = useWorkflowDiffStore.getState()
const pendingExternalUpdateBeforeApply =
diffStateBeforeApply.pendingExternalUpdates[workflowId] ?? 0
if (
diffStateBeforeApply.hasActiveDiff ||
pendingExternalUpdateBeforeApply > pendingExternalUpdateAtStart ||
useOperationQueueStore.getState().hasPendingOperations(workflowId)
) {
logger.info(`Deferring workflow reload apply after ${reason}`, { workflowId })
useWorkflowDiffStore.getState().markExternalUpdatePending(workflowId)
if (isLatestReload()) {
useWorkflowDiffStore.getState().setWorkflowReconciliationInProgress(workflowId, false)
if (useWorkflowRegistry.getState().activeWorkflowId === workflowId) {
void replayPendingExternalUpdate(
workflowId,
'deferred external update after reload apply was skipped'
)
}
}
return false
}
isApplyingRemoteChange.current = true
try {
const stateToApply: WorkflowState = {
blocks: workflowState.blocks || {},
edges: workflowState.edges || [],
loops: workflowState.loops || {},
parallels: workflowState.parallels || {},
lastSaved: workflowState.lastSaved || Date.now(),
}
if (Object.hasOwn(workflowState, 'variables')) {
stateToApply.variables = workflowState.variables || {}
}
applyWorkflowStateToStores(workflowId, stateToApply)
const graph = {
blocksById: workflowState.blocks || {},
edgesById: Object.fromEntries((workflowState.edges || []).map((e) => [e.id, e])),
}
const undoRedoStore = useUndoRedoStore.getState()
const stackKeys = Object.keys(undoRedoStore.stacks)
stackKeys.forEach((key) => {
const [wfId, userId] = key.split(':')
if (wfId === workflowId) {
undoRedoStore.pruneInvalidEntries(wfId, userId, graph)
}
})
logger.info(`Successfully reloaded workflow state after ${reason}`, { workflowId })
const diffStore = useWorkflowDiffStore.getState()
const pendingExternalUpdate = diffStore.pendingExternalUpdates[workflowId] ?? 0
if (pendingExternalUpdate <= pendingExternalUpdateAtStart) {
diffStore.clearExternalUpdatePending(workflowId)
}
diffStore.setWorkflowReconciliationError(workflowId, null)
return true
} finally {
isApplyingRemoteChange.current = false
if (isLatestReload()) {
useWorkflowDiffStore.getState().setWorkflowReconciliationInProgress(workflowId, false)
if (useWorkflowRegistry.getState().activeWorkflowId === workflowId) {
void replayPendingExternalUpdate(
workflowId,
'deferred external update after reconciliation'
)
}
}
}
}
const replayPendingExternalUpdate = async (workflowId: string, reason: string) => {
const diffStore = useWorkflowDiffStore.getState()
if (
useWorkflowRegistry.getState().activeWorkflowId !== workflowId ||
diffStore.hasActiveDiff ||
diffStore.reconcilingWorkflows[workflowId] ||
!diffStore.pendingExternalUpdates[workflowId]
) {
return
}
const queueStore = useOperationQueueStore.getState()
if (queueStore.hasPendingOperations(workflowId)) {
return
}
try {
await reloadWorkflowFromApi(workflowId, reason)
} catch (error) {
logger.error(`Error reloading workflow state after ${reason}:`, error)
}
}
const handleWorkflowReverted = async (data: any) => {
const { workflowId } = data
logger.info(`Workflow ${workflowId} has been reverted to deployed state`)
if (activeWorkflowId !== workflowId) return
useWorkflowDiffStore.getState().markRemoteUpdateSeen(workflowId)
try {
await reloadWorkflowFromApi(workflowId, 'revert')
} catch (error) {
logger.error('Error reloading workflow state after revert:', error)
}
}
const handleWorkflowUpdated = async (data: any) => {
const { workflowId } = data
logger.info(`Workflow ${workflowId} has been updated externally`)
if (activeWorkflowId !== workflowId) return
const diffStore = useWorkflowDiffStore.getState()
const { hasActiveDiff } = diffStore
if (hasActiveDiff) {
logger.info('Deferring workflow-updated: active diff in progress', { workflowId })
diffStore.markExternalUpdatePending(workflowId)
return
}
if (diffStore.reconcilingWorkflows[workflowId]) {
logger.info('Deferring workflow-updated: workflow reconciliation is in progress', {
workflowId,
})
diffStore.markExternalUpdatePending(workflowId)
return
}
const operationQueue = useOperationQueueStore.getState()
if (operationQueue.hasPendingOperations(workflowId)) {
logger.info('Deferring workflow-updated: local operations are still pending', {
workflowId,
})
diffStore.markExternalUpdatePending(workflowId)
void operationQueue.waitForWorkflowOperations(workflowId).then((ready) => {
if (!ready) {
const latestQueue = useOperationQueueStore.getState()
if (latestQueue.hasPendingOperations(workflowId) && !latestQueue.hasOperationError) {
return
}
const diffStore = useWorkflowDiffStore.getState()
diffStore.clearExternalUpdatePending(workflowId)
diffStore.setWorkflowReconciliationError(
workflowId,
'Failed to save local workflow changes before syncing external updates.'
)
return
}
void replayPendingExternalUpdate(workflowId, 'deferred external update after local save')
})
return
}
diffStore.markRemoteUpdateSeen(workflowId)
try {
await reloadWorkflowFromApi(workflowId, 'external update')
} catch (error) {
logger.error('Error reloading workflow state after external update:', error)
}
}
const handleDiffSettled = async (event: Event) => {
const customEvent = event as CustomEvent<{ workflowId?: string }>
const workflowId = customEvent.detail?.workflowId
if (!workflowId || activeWorkflowId !== workflowId) return
const diffStore = useWorkflowDiffStore.getState()
if (!diffStore.pendingExternalUpdates[workflowId]) return
await replayPendingExternalUpdate(workflowId, 'deferred external update')
}
const handleWorkflowDeployed = (data: any) => {
const { workflowId } = data
logger.info(`Workflow ${workflowId} deployment state changed`)
if (workflowId !== activeWorkflowId) return
invalidateDeploymentQueries(queryClient, workflowId)
}
const handleOperationConfirmed = (data: any) => {
const { operationId } = data
logger.debug('Operation confirmed', { operationId })
confirmOperation(operationId)
if (activeWorkflowId) {
void replayPendingExternalUpdate(
activeWorkflowId,
'deferred external update after operation confirm'
)
}
}
const handleOperationFailed = (data: any) => {
const { operationId, error, retryable } = data
logger.warn('Operation failed', { operationId, error, retryable })
failOperation(operationId, retryable)
}
onWorkflowOperation(handleWorkflowOperation)
onSubblockUpdate(handleSubblockUpdate)
onVariableUpdate(handleVariableUpdate)
onWorkflowDeleted(handleWorkflowDeleted)
onWorkflowReverted(handleWorkflowReverted)
onWorkflowUpdated(handleWorkflowUpdated)
onWorkflowDeployed(handleWorkflowDeployed)
onOperationConfirmed(handleOperationConfirmed)
onOperationFailed(handleOperationFailed)
window.addEventListener(WORKFLOW_DIFF_SETTLED_EVENT, handleDiffSettled)
if (activeWorkflowId) {
void replayPendingExternalUpdate(
activeWorkflowId,
'pending external update after workflow activation'
)
}
return () => {
window.removeEventListener(WORKFLOW_DIFF_SETTLED_EVENT, handleDiffSettled)
}
}, [
onWorkflowOperation,
onSubblockUpdate,
onVariableUpdate,
onWorkflowDeleted,
onWorkflowReverted,
onWorkflowUpdated,
onWorkflowDeployed,
onOperationConfirmed,
onOperationFailed,
activeWorkflowId,
queryClient,
confirmOperation,
failOperation,
emitWorkflowOperation,
])
const executeQueuedOperation = useCallback(
(operation: string, target: string, payload: any, localAction: () => void) => {
if (isApplyingRemoteChange.current) {
return
}
// Skip socket operations when viewing baseline diff (readonly)
if (isBaselineDiffView) {
logger.debug('Skipping socket operation while viewing baseline diff:', operation)
return
}
// Queue operations if we have an active workflow - queue handles socket readiness
if (!activeWorkflowId) {
logger.debug('Skipping operation - no active workflow', { operation, target })
return
}
const operationId = generateId()
addToQueue({
id: operationId,
operation: {
operation,
target,
payload,
},
workflowId: activeWorkflowId,
userId: session?.user?.id || 'unknown',
})
localAction()
},
[addToQueue, session?.user?.id, isBaselineDiffView, activeWorkflowId]
)
const collaborativeBatchUpdatePositions = useCallback(
(
updates: Array<{ id: string; position: Position }>,
options?: {
previousPositions?: Map<string, { x: number; y: number; parentId?: string }>
}
) => {
if (isBaselineDiffView) {
return
}
if (!activeWorkflowId) {
logger.debug('Skipping batch position update - no active workflow')
return
}
if (updates.length === 0) return
const operationId = generateId()
addToQueue({
id: operationId,
operation: {
operation: BLOCKS_OPERATIONS.BATCH_UPDATE_POSITIONS,
target: OPERATION_TARGETS.BLOCKS,
payload: { updates },
},
workflowId: activeWorkflowId || '',
userId: session?.user?.id || 'unknown',
})
useWorkflowStore.getState().batchUpdatePositions(updates)
if (options?.previousPositions && options.previousPositions.size > 0) {
const moves = updates
.filter((u) => options.previousPositions!.has(u.id))
.map((u) => {
const prev = options.previousPositions!.get(u.id)!
const block = useWorkflowStore.getState().blocks[u.id]
return {
blockId: u.id,
before: prev,
after: {
x: u.position.x,
y: u.position.y,
parentId: block?.data?.parentId,
},
}
})
.filter((m) => m.before.x !== m.after.x || m.before.y !== m.after.y)
if (moves.length > 0) {