forked from simstudioai/sim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff-engine.ts
More file actions
375 lines (326 loc) · 10.6 KB
/
Copy pathdiff-engine.ts
File metadata and controls
375 lines (326 loc) · 10.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
import { createLogger } from '@/lib/logs/console/logger'
import { mergeSubblockState } from '@/stores/workflows/utils'
import type { BlockState, WorkflowState } from '@/stores/workflows/workflow/types'
import type { BlockWithDiff } from './types'
const logger = createLogger('WorkflowDiffEngine')
export interface DiffMetadata {
source: string
timestamp: number
}
export interface EdgeDiff {
new_edges: string[]
deleted_edges: string[]
unchanged_edges: string[]
}
export interface DiffAnalysis {
new_blocks: string[]
edited_blocks: string[]
deleted_blocks: string[]
field_diffs?: Record<string, { changed_fields: string[]; unchanged_fields: string[] }>
edge_diff?: EdgeDiff
}
export interface WorkflowDiff {
proposedState: WorkflowState
diffAnalysis?: DiffAnalysis
metadata: DiffMetadata
}
export interface DiffResult {
success: boolean
diff?: WorkflowDiff
errors?: string[]
}
/**
* Clean diff engine that handles workflow diff operations
* without polluting core workflow stores
*/
export class WorkflowDiffEngine {
private currentDiff: WorkflowDiff | undefined = undefined
/**
* Create a diff from YAML content
*/
async createDiffFromYaml(yamlContent: string, diffAnalysis?: DiffAnalysis): Promise<DiffResult> {
try {
logger.info('WorkflowDiffEngine.createDiffFromYaml called with:', {
yamlContentLength: yamlContent.length,
diffAnalysis: diffAnalysis,
diffAnalysisType: typeof diffAnalysis,
diffAnalysisUndefined: diffAnalysis === undefined,
diffAnalysisNull: diffAnalysis === null,
})
// Get current workflow state for comparison
const { useWorkflowStore } = await import('@/stores/workflows/workflow/store')
const currentWorkflowState = useWorkflowStore.getState().getWorkflowState()
logger.info('WorkflowDiffEngine current workflow state:', {
blockCount: Object.keys(currentWorkflowState.blocks || {}).length,
edgeCount: currentWorkflowState.edges?.length || 0,
hasLoops: Object.keys(currentWorkflowState.loops || {}).length > 0,
hasParallels: Object.keys(currentWorkflowState.parallels || {}).length > 0,
})
// Merge subblock values from subblock store to ensure manual edits are included in baseline
let mergedBaseline: WorkflowState = currentWorkflowState
try {
mergedBaseline = {
...currentWorkflowState,
blocks: mergeSubblockState(currentWorkflowState.blocks),
}
logger.info('Merged subblock values into baseline for diff creation', {
blockCount: Object.keys(mergedBaseline.blocks || {}).length,
})
} catch (mergeError) {
logger.warn('Failed to merge subblock values into baseline; proceeding with raw state', {
error: mergeError instanceof Error ? mergeError.message : String(mergeError),
})
}
// Call the API route to create the diff
const body: any = {
yamlContent,
currentWorkflowState: mergedBaseline,
}
if (diffAnalysis !== undefined && diffAnalysis !== null) {
body.diffAnalysis = diffAnalysis
}
body.options = {
applyAutoLayout: true,
layoutOptions: {
strategy: 'smart',
direction: 'auto',
spacing: {
horizontal: 500,
vertical: 400,
layer: 700,
},
alignment: 'center',
padding: {
x: 250,
y: 250,
},
},
}
const response = await fetch('/api/yaml/diff/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
if (!response.ok) {
const errorData = await response.json().catch(() => null)
logger.error('Failed to create diff:', {
status: response.status,
error: errorData,
})
return {
success: false,
errors: [errorData?.error || `Failed to create diff: ${response.statusText}`],
}
}
const result = await response.json()
logger.info('WorkflowDiffEngine.createDiffFromYaml response:', {
success: result.success,
hasDiff: !!result.diff,
errors: result.errors,
hasDiffAnalysis: !!result.diff?.diffAnalysis,
})
if (!result.success || !result.diff) {
return {
success: false,
errors: result.errors,
}
}
// Log diff analysis details
if (result.diff.diffAnalysis) {
logger.info('WorkflowDiffEngine diff analysis:', {
new_blocks: result.diff.diffAnalysis.new_blocks,
edited_blocks: result.diff.diffAnalysis.edited_blocks,
deleted_blocks: result.diff.diffAnalysis.deleted_blocks,
field_diffs: result.diff.diffAnalysis.field_diffs
? Object.keys(result.diff.diffAnalysis.field_diffs)
: [],
edge_diff: result.diff.diffAnalysis.edge_diff
? {
new_edges_count: result.diff.diffAnalysis.edge_diff.new_edges.length,
deleted_edges_count: result.diff.diffAnalysis.edge_diff.deleted_edges.length,
unchanged_edges_count: result.diff.diffAnalysis.edge_diff.unchanged_edges.length,
}
: null,
})
} else {
logger.warn('WorkflowDiffEngine: No diff analysis in response!')
}
// Store the current diff
this.currentDiff = result.diff
logger.info('Diff created successfully', {
blocksCount: Object.keys(result.diff.proposedState.blocks).length,
edgesCount: result.diff.proposedState.edges.length,
hasDiffAnalysis: !!result.diff.diffAnalysis,
})
return {
success: true,
diff: this.currentDiff,
}
} catch (error) {
logger.error('Failed to create diff:', error)
return {
success: false,
errors: [error instanceof Error ? error.message : 'Failed to create diff'],
}
}
}
/**
* Merge new YAML content into existing diff
* Used for cumulative updates within the same message
*/
async mergeDiffFromYaml(yamlContent: string, diffAnalysis?: DiffAnalysis): Promise<DiffResult> {
try {
logger.info('Merging diff from YAML content')
// If no existing diff, create a new one
if (!this.currentDiff) {
logger.info('No existing diff, creating new diff')
return this.createDiffFromYaml(yamlContent, diffAnalysis)
}
// Call the API route to merge the diff
const body: any = {
existingDiff: this.currentDiff,
yamlContent,
}
if (diffAnalysis !== undefined && diffAnalysis !== null) {
body.diffAnalysis = diffAnalysis
}
body.options = {
applyAutoLayout: true,
layoutOptions: {
strategy: 'smart',
direction: 'auto',
spacing: {
horizontal: 500,
vertical: 400,
layer: 700,
},
alignment: 'center',
padding: {
x: 250,
y: 250,
},
},
}
const response = await fetch('/api/yaml/diff/merge', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
if (!response.ok) {
const errorData = await response.json().catch(() => null)
logger.error('Failed to merge diff:', {
status: response.status,
error: errorData,
})
return {
success: false,
errors: [errorData?.error || `Failed to merge diff: ${response.statusText}`],
}
}
const result = await response.json()
if (!result.success || !result.diff) {
return {
success: false,
errors: result.errors,
}
}
// Update the current diff
this.currentDiff = result.diff
logger.info('Diff merged successfully', {
totalBlocksCount: Object.keys(result.diff.proposedState.blocks).length,
totalEdgesCount: result.diff.proposedState.edges.length,
})
return {
success: true,
diff: this.currentDiff,
}
} catch (error) {
logger.error('Failed to merge diff:', error)
return {
success: false,
errors: [error instanceof Error ? error.message : 'Failed to merge diff'],
}
}
}
/**
* Get the current diff
*/
getCurrentDiff(): WorkflowDiff | undefined {
return this.currentDiff
}
/**
* Clear the current diff
*/
clearDiff(): void {
this.currentDiff = undefined
logger.info('Diff cleared')
}
/**
* Check if a diff is active
*/
hasDiff(): boolean {
return this.currentDiff !== undefined
}
/**
* Get the workflow state for display (either diff or provided state)
*/
getDisplayState(currentState: WorkflowState): WorkflowState {
if (this.currentDiff) {
return this.currentDiff.proposedState
}
return currentState
}
/**
* Accept the diff and return the clean state
*/
acceptDiff(): WorkflowState | null {
if (!this.currentDiff) {
logger.warn('No diff to accept')
return null
}
try {
// Clean up the proposed state by removing diff markers
const cleanState = this.cleanDiffMarkers(this.currentDiff.proposedState)
logger.info('Diff accepted', {
blocksCount: Object.keys(cleanState.blocks).length,
edgesCount: cleanState.edges.length,
loopsCount: Object.keys(cleanState.loops).length,
parallelsCount: Object.keys(cleanState.parallels).length,
})
this.clearDiff()
return cleanState
} catch (error) {
logger.error('Failed to accept diff:', error)
return null
}
}
/**
* Clean diff markers from a workflow state
*/
private cleanDiffMarkers(state: WorkflowState): WorkflowState {
const cleanBlocks: Record<string, BlockState> = {}
// Remove diff markers from each block
for (const [blockId, block] of Object.entries(state.blocks)) {
const cleanBlock: BlockState = { ...block }
// Remove diff markers using proper typing
const blockWithDiff = cleanBlock as BlockState & BlockWithDiff
blockWithDiff.is_diff = undefined
blockWithDiff.field_diffs = undefined
// Ensure outputs is never null/undefined
if (cleanBlock.outputs === undefined || cleanBlock.outputs === null) {
cleanBlock.outputs = {}
}
cleanBlocks[blockId] = cleanBlock
}
return {
blocks: cleanBlocks,
edges: state.edges || [],
loops: state.loops || {},
parallels: state.parallels || {},
}
}
}