Line data Source code
1 : import { useDebounceFn } from '@vueuse/core'
2 : import _ from 'es-toolkit/compat'
3 :
4 : import { assert } from '@/base/assert'
5 : import { LAYER_EDITOR_DIALOG_KEY } from '@/renderer/extensions/layerEditor/layerEditorDialogKey'
6 : import { TEXT_EDITOR_DIALOG_KEY } from '@/renderer/extensions/textEditor/textEditorDialogKey'
7 : import type { CanvasPointerEvent } from '@/lib/litegraph/src/litegraph'
8 : import { LGraphCanvas, LiteGraph } from '@/lib/litegraph/src/litegraph'
9 : import type {
10 : ComfyWorkflow,
11 : WorkflowChangeTracker
12 : } from '@/platform/workflow/management/stores/comfyWorkflow'
13 : import { reportWorkflowStateAnomaly } from '@/platform/workflow/management/stores/comfyWorkflow'
14 : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
15 : import { isChangeCaptureSuppressed } from '@/services/changeCaptureSuppression'
16 : import type { ComfyWorkflowJSON } from '@comfyorg/graph-model/workflowSchema'
17 : import {
18 : collectSubgraphDefinitions,
19 : parseFlattenableSubgraphDefinitions
20 : } from '@/platform/workflow/core/utils/workflowFlattening'
21 : import type { ExecutedWsMessage } from '@comfyorg/api-client/executionTypes'
22 : import {
23 : canCaptureCanvas,
24 : isCanvasCaptureBlocked,
25 : resetCanvasTrackerForTest
26 : } from '@/platform/workflow/core/canvasTrackerOwnership'
27 : import { useDialogStore } from '@/stores/dialogStore'
28 : import { useExecutionStore } from '@/stores/executionStore'
29 : import { useNodeOutputStore } from '@/stores/nodeOutputStore'
30 : import { useQueueSettingsStore } from '@/stores/queueSettingsStore'
31 : import { useSubgraphNavigationStore } from '@/stores/subgraphNavigationStore'
32 : import { useWidgetHistoryStore } from '@/stores/widgetHistoryStore'
33 : import { serializeNodeId } from '@comfyorg/graph-model/nodeId'
34 : import { isSelectOnly } from '@/utils/litegraphUtil'
35 : import { isModalOpen } from '@/utils/modalUtil'
36 :
37 : import { api } from './api'
38 : import {
39 : collectNodeHistoryWidgets,
40 : nodeHistoryValuesChanged,
41 : withNodeHistoryValuesFrom
42 : } from './nodeHistoryWidgetValues'
43 : import { useApp } from '@/scripts/appInstance'
44 : import { provideChangeTracker } from '@/scripts/changeTrackerAccess'
45 : import { clipspace } from '@/scripts/clipspace'
46 : import { travelFocusedNodeHistory } from '@/scripts/focusedNodeHistory'
47 :
48 10448 : function clone<T>(obj: T): T {
49 10448 : return JSON.parse(JSON.stringify(obj))
50 : }
51 :
52 22916 : function withoutExecutionOrder(nodes: ComfyWorkflowJSON['nodes']) {
53 22916 : return nodes.map((node) => _.omit(node, ['order']))
54 : }
55 :
56 0 : function withNormalizedNodeSizes(state: ComfyWorkflowJSON): ComfyWorkflowJSON {
57 0 : const comparable = clone(state)
58 0 : const subgraphs = collectSubgraphDefinitions(
59 : parseFlattenableSubgraphDefinitions(comparable.definitions?.subgraphs ?? [])
60 : )
61 0 : const nodes = [
62 : ...comparable.nodes,
63 : ...subgraphs.flatMap((subgraph) => subgraph.nodes)
64 : ]
65 0 : for (const node of nodes) {
66 0 : if ('size' in node) node.size = [0, 0]
67 : }
68 0 : return comparable
69 : }
70 :
71 0 : function matchesRestoredTarget(
72 : actual: ComfyWorkflowJSON,
73 : target: ComfyWorkflowJSON,
74 : previous: ComfyWorkflowJSON
75 : ): boolean {
76 0 : if (ChangeTracker.graphEqual(actual, target)) return true
77 0 : const comparableTarget = withNormalizedNodeSizes(target)
78 0 : return (
79 : ChangeTracker.graphEqual(
80 : withNormalizedNodeSizes(actual),
81 : comparableTarget
82 : ) &&
83 : !ChangeTracker.graphEqual(
84 : comparableTarget,
85 : withNormalizedNodeSizes(previous)
86 : )
87 : )
88 : }
89 :
90 : type NodeHistoryWidgets = ReturnType<typeof collectNodeHistoryWidgets>
91 :
92 1379 : function differsOnlyInNodeHistoryWidgets(
93 : previous: ComfyWorkflowJSON,
94 : current: ComfyWorkflowJSON,
95 : widgets: NodeHistoryWidgets
96 : ): boolean {
97 1379 : const { rootGraph } = useApp()
98 1379 : return (
99 : widgets.size > 0 &&
100 : nodeHistoryValuesChanged(previous, current, widgets, rootGraph.id) &&
101 : ChangeTracker.graphEqual(
102 : withNodeHistoryValuesFrom(previous, current, widgets, rootGraph.id),
103 : current
104 : )
105 : )
106 : }
107 :
108 76 : function keepingLiveNodeHistoryValues(
109 : target: ComfyWorkflowJSON
110 : ): ComfyWorkflowJSON {
111 76 : const { rootGraph } = useApp()
112 76 : const widgets = collectNodeHistoryWidgets(rootGraph)
113 76 : if (!widgets.size) return target
114 : const live = clone(rootGraph.serialize()) as ComfyWorkflowJSON
115 0 : return withNodeHistoryValuesFrom(target, live, widgets, rootGraph.id)
116 : }
117 :
118 1455 : function forgetRemovedNodeHistories(widgets: NodeHistoryWidgets): void {
119 1455 : useWidgetHistoryStore().retainLive(useApp().rootGraph.id, widgets)
120 : }
121 :
122 10566 : function isActiveTracker(tracker: ChangeTracker): boolean {
123 10566 : return useWorkflowStore().activeWorkflow?.changeTracker === tracker
124 : }
125 :
126 1461 : function historyShortcut(e: KeyboardEvent): 'undo' | 'redo' | undefined {
127 1461 : if (!(e.ctrlKey || e.metaKey) || e.altKey) return
128 913 : const key = e.key.toUpperCase()
129 1461 : if (key === 'Y' && !e.shiftKey) return 'redo'
130 1000 : if (key === 'Z') return e.shiftKey ? 'redo' : 'undo'
131 : }
132 :
133 3648 : function isAutoQueueOnChange(): boolean {
134 3648 : const { ui } = useApp()
135 3648 : return (
136 : useQueueSettingsStore().mode === 'change' ||
137 : (ui.autoQueueEnabled && ui.autoQueueMode === 'change')
138 : )
139 : }
140 :
141 2356 : const nonExecutionGraphProperties = new Set([
142 : 'id',
143 : 'revision',
144 : 'last_node_id',
145 : 'last_link_id',
146 : 'state',
147 : 'groups',
148 : 'config',
149 : 'extra',
150 : 'version',
151 : 'models',
152 : 'reroutes',
153 : 'floatingLinks',
154 : 'subgraphs',
155 : 'definitions',
156 : 'name',
157 : 'description',
158 : 'category',
159 : 'essentials_category'
160 : ])
161 :
162 2356 : const nonExecutionNodeProperties = new Set([
163 : 'pos',
164 : 'size',
165 : // Node flags, including skip_repeated_outputs, only affect the editor.
166 : 'flags',
167 : 'order',
168 : 'color',
169 : 'bgcolor',
170 : 'boxcolor',
171 : 'shape',
172 : 'showAdvanced',
173 : 'title'
174 : ])
175 :
176 2356 : const nonExecutionSlotProperties = new Set([
177 : 'localized_name',
178 : 'label',
179 : 'shape',
180 : 'color_off',
181 : 'color_on',
182 : 'pos',
183 : 'link',
184 : 'links',
185 : 'linkIds',
186 : 'slot_index'
187 : ])
188 :
189 2356 : const nonExecutionBoundaryNodeProperties = new Set(['bounding', 'pinned'])
190 2356 : const nonExecutableNodeTypes = new Set(['Note', 'MarkdownNote'])
191 :
192 872 : function isRecord(value: unknown): value is Record<string, unknown> {
193 872 : return typeof value === 'object' && value !== null && !Array.isArray(value)
194 : }
195 :
196 872 : function asRecord(value: unknown): Record<string, unknown> | null {
197 872 : return isRecord(value) ? value : null
198 : }
199 :
200 644 : function omitProperties(
201 : record: Record<string, unknown>,
202 : properties: ReadonlySet<string>
203 : ): Record<string, unknown> {
204 644 : return Object.fromEntries(
205 : Object.entries(record).filter(([key]) => !properties.has(key))
206 : )
207 : }
208 :
209 512 : function getExecutionSlotState(value: unknown): unknown {
210 512 : const slot = asRecord(value)
211 512 : return slot ? omitProperties(slot, nonExecutionSlotProperties) : value
212 : }
213 :
214 114 : function getExecutionNodeState(value: unknown): unknown {
215 114 : const node = asRecord(value)
216 114 : if (!node) return value
217 :
218 114 : const executionNode = omitProperties(node, nonExecutionNodeProperties)
219 114 : if ('id' in node) {
220 114 : executionNode.id = normalizeNodeId(node.id)
221 : }
222 114 : if (Array.isArray(node.inputs)) {
223 114 : executionNode.inputs = node.inputs.map(getExecutionSlotState)
224 : }
225 114 : if (Array.isArray(node.outputs)) {
226 114 : executionNode.outputs = node.outputs.map(getExecutionSlotState)
227 : }
228 114 : return executionNode
229 : }
230 :
231 0 : function getExecutionBoundaryNodeState(value: unknown): unknown {
232 0 : const node = asRecord(value)
233 0 : if (!node) return value
234 :
235 0 : const executionNode = omitProperties(node, nonExecutionBoundaryNodeProperties)
236 0 : if ('id' in node) {
237 0 : executionNode.id = normalizeNodeId(node.id)
238 : }
239 0 : return executionNode
240 : }
241 :
242 144 : function getExecutionLinkState(value: unknown): unknown {
243 144 : if (Array.isArray(value)) {
244 144 : return [
245 : normalizeNodeId(value[1]),
246 : normalizeSlotIndex(value[2]),
247 : normalizeNodeId(value[3]),
248 : normalizeSlotIndex(value[4])
249 : ]
250 : }
251 :
252 0 : const link = asRecord(value)
253 0 : if (!link) return value
254 0 : return [
255 : normalizeNodeId(link.origin_id),
256 : normalizeSlotIndex(link.origin_slot),
257 : normalizeNodeId(link.target_id),
258 : normalizeSlotIndex(link.target_slot)
259 : ]
260 : }
261 :
262 402 : function normalizeNodeId(value: unknown): unknown {
263 402 : return typeof value === 'number' || typeof value === 'string'
264 : ? serializeNodeId(value)
265 : : value
266 : }
267 :
268 288 : function normalizeSlotIndex(value: unknown): unknown {
269 288 : if (typeof value !== 'string') return value
270 :
271 0 : const index = parseInt(value)
272 288 : return Number.isNaN(index) ? value : index
273 : }
274 :
275 114 : function isExecutableNodeState(value: unknown): boolean {
276 114 : const node = asRecord(value)
277 114 : return (
278 : !node ||
279 : typeof node.type !== 'string' ||
280 : !nonExecutableNodeTypes.has(node.type)
281 : )
282 : }
283 :
284 0 : function getExecutionDefinitionsState(value: unknown): unknown {
285 0 : const definitions = asRecord(value)
286 0 : if (!definitions || !Array.isArray(definitions.subgraphs)) return value
287 :
288 0 : return {
289 : ...definitions,
290 : subgraphs: _.sortBy(
291 : definitions.subgraphs,
292 : (subgraph) => asRecord(subgraph)?.id
293 : ).map(getExecutionGraphState)
294 : }
295 : }
296 :
297 18 : function getExecutionGraphState(value: unknown): unknown {
298 18 : const graph = asRecord(value)
299 18 : if (!graph) return value
300 :
301 18 : const executionGraph = omitProperties(graph, nonExecutionGraphProperties)
302 18 : if (Array.isArray(graph.nodes)) {
303 18 : executionGraph.nodes = _.sortBy(
304 : graph.nodes.filter(isExecutableNodeState).map(getExecutionNodeState),
305 : (node) => asRecord(node)?.id
306 : )
307 : }
308 18 : if (Array.isArray(graph.links)) {
309 18 : executionGraph.links = _.sortBy(
310 : graph.links.map(getExecutionLinkState),
311 : (link) => JSON.stringify(link)
312 : )
313 0 : } else if (!('links' in graph)) {
314 0 : executionGraph.links = []
315 : }
316 18 : if (Array.isArray(graph.inputs)) {
317 0 : executionGraph.inputs = graph.inputs.map(getExecutionSlotState)
318 : }
319 18 : if (Array.isArray(graph.outputs)) {
320 0 : executionGraph.outputs = graph.outputs.map(getExecutionSlotState)
321 : }
322 18 : if ('inputNode' in graph) {
323 0 : executionGraph.inputNode = getExecutionBoundaryNodeState(graph.inputNode)
324 : }
325 18 : if ('outputNode' in graph) {
326 0 : executionGraph.outputNode = getExecutionBoundaryNodeState(graph.outputNode)
327 : }
328 18 : if ('definitions' in graph) {
329 0 : executionGraph.definitions = getExecutionDefinitionsState(graph.definitions)
330 : }
331 18 : return executionGraph
332 : }
333 :
334 2356 : const reportedInactiveCalls = new Set<string>()
335 :
336 0 : function reportInactiveTrackerCall(method: string, workflowPath: string) {
337 0 : const key = `${method}:${workflowPath}`
338 0 : if (reportedInactiveCalls.has(key)) return
339 0 : reportedInactiveCalls.add(key)
340 0 : assert(false, `ChangeTracker.${method}() called on inactive tracker`)
341 : }
342 :
343 2356 : const reportedCanvasMismatchCalls = new Set<string>()
344 :
345 4 : function reportCanvasMismatchCall(method: string, workflowPath: string) {
346 4 : const key = `${method}:${workflowPath}`
347 4 : if (reportedCanvasMismatchCalls.has(key)) return
348 1 : reportedCanvasMismatchCalls.add(key)
349 1 : assert(
350 : false,
351 : `ChangeTracker.${method}() called while another workflow's graph is on the canvas`
352 : )
353 : }
354 :
355 2356 : export class ChangeTracker implements WorkflowChangeTracker {
356 : static MAX_HISTORY = 50
357 :
358 : static resetCanvasTrackerForTest() {
359 0 : resetCanvasTrackerForTest()
360 0 : reportedCanvasMismatchCalls.clear()
361 : }
362 : /**
363 : * Guard flag to prevent captureCanvasState from running during loadGraphData.
364 : * Between rootGraph.configure() and afterLoadNewGraph(), the rootGraph
365 : * contains the NEW workflow's data while activeWorkflow still points to
366 : * the OLD workflow. Any captureCanvasState call in that window would
367 : * serialize the wrong graph into the old workflow's activeState, corrupting it.
368 : */
369 : static isLoadingGraph = false
370 :
371 : /**
372 : * The active state of the workflow.
373 : */
374 : activeState: ComfyWorkflowJSON
375 : undoQueue: ComfyWorkflowJSON[] = []
376 : redoQueue: ComfyWorkflowJSON[] = []
377 : changeCount: number = 0
378 : /**
379 : * Whether the redo/undo restoring is in progress.
380 : */
381 : _restoringState: boolean = false
382 : private restoreChain?: Promise<void>
383 :
384 : ds?: { scale: number; offset: [number, number] }
385 : nodeOutputs?: Partial<Record<string, ExecutedWsMessage['output']>>
386 :
387 : private subgraphState?: {
388 : navigation: string[]
389 : }
390 :
391 : constructor(
392 : /**
393 : * The workflow that this change tracker is tracking
394 : */
395 266605 : public workflow: ComfyWorkflow,
396 : /**
397 : * The initial state of the workflow
398 : */
399 266605 : public initialState: ComfyWorkflowJSON
400 : ) {
401 266605 : this.activeState = initialState
402 : }
403 :
404 : /**
405 : * Save the current state as the initial state.
406 : */
407 : reset(state?: ComfyWorkflowJSON) {
408 466 : if (state) this.activeState = clone(state)
409 466 : if (this._restoringState) return
410 :
411 390 : this.initialState = clone(this.activeState)
412 : }
413 :
414 : store() {
415 1548 : const { ds } = useApp().canvas
416 1548 : this.ds = { scale: ds.scale, offset: [ds.offset[0], ds.offset[1]] }
417 1548 : this.nodeOutputs = useNodeOutputStore().snapshotOutputs()
418 1548 : const navigation = useSubgraphNavigationStore().exportState()
419 : // Always store the navigation state, even if empty (root level)
420 1548 : this.subgraphState = { navigation }
421 : }
422 :
423 : /**
424 : * Freeze this tracker's state before the workflow goes inactive.
425 : * Always calls store() to preserve viewport/outputs. Calls
426 : * captureCanvasState() only when not in undo/redo (to avoid
427 : * corrupting undo history with intermediate graph state).
428 : *
429 : * PRECONDITION: must be called while this workflow is still the active one
430 : * (before the activeWorkflow pointer is moved). If called after the pointer
431 : * has already moved, this is a no-op to avoid freezing wrong viewport data.
432 : *
433 : * @internal Not part of the public extension API.
434 : */
435 : deactivate() {
436 1548 : if (!isActiveTracker(this)) {
437 0 : reportInactiveTrackerCall('deactivate', this.workflow.path)
438 0 : return
439 : }
440 1548 : if (!this._restoringState && canCaptureCanvas(this)) {
441 1472 : this.captureCanvasState()
442 : }
443 1548 : this.store()
444 : }
445 :
446 : /**
447 : * Ensure activeState is up-to-date for persistence.
448 : * Active workflow: flushes canvas → activeState.
449 : * Inactive workflow: no-op (activeState was frozen by deactivate()).
450 : *
451 : * @internal Not part of the public extension API.
452 : */
453 : prepareForSave() {
454 300 : if (isActiveTracker(this) && canCaptureCanvas(this)) {
455 131 : this.captureCanvasState()
456 : }
457 : }
458 :
459 : restore() {
460 273 : const app = useApp()
461 273 : if (this.ds) {
462 183 : app.canvas.ds.scale = this.ds.scale
463 183 : app.canvas.ds.offset = this.ds.offset
464 : }
465 273 : if (this.nodeOutputs) {
466 183 : useNodeOutputStore().restoreOutputs(this.nodeOutputs)
467 : }
468 273 : if (this.subgraphState) {
469 183 : const { navigation } = this.subgraphState
470 183 : const firstInvalidIndex = navigation.findIndex(
471 : (id) => !app.rootGraph.subgraphs.has(id)
472 : )
473 183 : if (firstInvalidIndex !== -1) navigation.splice(firstInvalidIndex)
474 183 : useSubgraphNavigationStore().restoreState(navigation)
475 :
476 183 : const activeId = navigation.at(-1)
477 183 : if (activeId) {
478 : // Navigate to the saved subgraph
479 5 : const subgraph = app.rootGraph.subgraphs.get(activeId)
480 5 : if (subgraph) {
481 5 : app.canvas.setGraph(subgraph)
482 : }
483 : } else {
484 : // Empty navigation array means root level
485 178 : app.canvas.setGraph(app.rootGraph)
486 : }
487 : }
488 : }
489 :
490 : updateModified(previousState?: ComfyWorkflowJSON) {
491 : // Get the workflow from the store as ChangeTracker is raw object, i.e.
492 : // `this.workflow` is not reactive.
493 1580 : const workflow = useWorkflowStore().getWorkflowByPath(this.workflow.path)
494 1580 : if (workflow) {
495 : // Declared non-null, but a tracker can still lack it at runtime.
496 1580 : const initialState = this.initialState as ComfyWorkflowJSON | null
497 1580 : if (initialState) {
498 1580 : workflow.isModified = !ChangeTracker.graphEqual(
499 : initialState,
500 : this.activeState
501 : )
502 : } else {
503 0 : reportWorkflowStateAnomaly(
504 : 'ChangeTracker has no initial state',
505 : 'ChangeTracker.updateModified',
506 : workflow,
507 : { isActive: isActiveTracker(this) }
508 : )
509 : }
510 : }
511 :
512 1580 : const autoQueueGraphChanged =
513 : !!previousState &&
514 : isAutoQueueOnChange() &&
515 : !_.isEqual(
516 : getExecutionGraphState(previousState),
517 : getExecutionGraphState(this.activeState)
518 : )
519 :
520 1580 : api.dispatchCustomEvent('graphChanged', this.activeState)
521 1580 : if (autoQueueGraphChanged) {
522 8 : api.dispatchCustomEvent('autoQueueGraphChanged')
523 : }
524 : }
525 :
526 : /**
527 : * Snapshot the current canvas state into activeState and push undo.
528 : * INVARIANT: only the active workflow's tracker may read from the canvas.
529 : * Calling this on an inactive tracker would capture the wrong graph.
530 : */
531 : captureCanvasState() {
532 8792 : const isUndoRedoing = this._restoringState
533 8792 : const isInsideChangeTransaction = this.changeCount > 0
534 8792 : if (
535 : !useApp().isGraphReady ||
536 : isInsideChangeTransaction ||
537 : isUndoRedoing ||
538 : ChangeTracker.isLoadingGraph ||
539 : isChangeCaptureSuppressed()
540 : )
541 83 : return
542 :
543 8788 : if (!isActiveTracker(this)) {
544 0 : reportInactiveTrackerCall('captureCanvasState', this.workflow.path)
545 0 : return
546 : }
547 8788 : if (isCanvasCaptureBlocked()) return
548 8788 : if (!canCaptureCanvas(this)) {
549 4 : reportCanvasMismatchCall('captureCanvasState', this.workflow.path)
550 4 : return
551 : }
552 :
553 8700 : const currentState = clone(
554 : useApp().rootGraph.serialize()
555 : ) as ComfyWorkflowJSON
556 8788 : if (!ChangeTracker.graphEqual(this.activeState, currentState)) {
557 1379 : const previousState = this.activeState
558 1379 : const nodeHistoryWidgets = collectNodeHistoryWidgets(useApp().rootGraph)
559 1379 : if (
560 : !differsOnlyInNodeHistoryWidgets(
561 : previousState,
562 : currentState,
563 : nodeHistoryWidgets
564 : )
565 : ) {
566 1360 : this.undoQueue.push(previousState)
567 1360 : if (this.undoQueue.length > ChangeTracker.MAX_HISTORY) {
568 0 : this.undoQueue.shift()
569 : }
570 1360 : this.redoQueue.length = 0
571 : }
572 :
573 1379 : this.activeState = currentState
574 1379 : this.updateModified(previousState)
575 1379 : forgetRemovedNodeHistories(nodeHistoryWidgets)
576 1379 : void this.squashState()
577 : }
578 : }
579 : squashState = useDebounceFn(() => {
580 1120 : if (
581 : this !== useWorkflowStore().activeWorkflow?.changeTracker ||
582 : ChangeTracker.isLoadingGraph ||
583 : isChangeCaptureSuppressed() ||
584 : !canCaptureCanvas(this)
585 : )
586 71 : return
587 :
588 1049 : const currentState = clone(
589 : useApp().rootGraph.serialize()
590 : ) as ComfyWorkflowJSON
591 1054 : if (ChangeTracker.graphEqual(this.activeState, currentState)) return
592 :
593 124 : const previousState = this.activeState
594 124 : this.activeState = currentState
595 124 : this.updateModified(previousState)
596 : }, 50)
597 :
598 : /**
599 : * Marks the workflow modified and sends graphChanged with the committed
600 : * state, without adding undo history or reading the canvas.
601 : */
602 : markModified() {
603 9 : if (!isActiveTracker(this) || ChangeTracker.isLoadingGraph) return
604 :
605 9 : const workflow = useWorkflowStore().getWorkflowByPath(this.workflow.path)
606 9 : if (workflow) workflow.isModified = true
607 9 : api.dispatchCustomEvent('graphChanged', this.activeState)
608 : }
609 :
610 : /** @deprecated Use {@link captureCanvasState} instead. */
611 : checkState() {
612 0 : if (!ChangeTracker._checkStateWarned) {
613 0 : ChangeTracker._checkStateWarned = true
614 0 : console.warn(
615 : 'checkState() is deprecated — use captureCanvasState() instead.'
616 : )
617 : }
618 0 : this.captureCanvasState()
619 : }
620 :
621 : private static _checkStateWarned = false
622 :
623 : static resetCheckStateWarningForTest() {
624 0 : ChangeTracker._checkStateWarned = false
625 : }
626 :
627 : async updateState(source: ComfyWorkflowJSON[], target: ComfyWorkflowJSON[]) {
628 82 : const restore = async () => {
629 82 : if (this._restoringState || source.length === 0) return
630 76 : const prevState = source.pop()
631 76 : if (prevState) {
632 76 : const previousState = this.activeState
633 76 : const targetState = keepingLiveNodeHistoryValues(prevState)
634 76 : const restoresSavedState = ChangeTracker.graphEqual(
635 : targetState,
636 : this.initialState
637 : )
638 76 : let restored = false
639 76 : this._restoringState = true
640 76 : try {
641 76 : const result = await useApp().loadGraphData(
642 : targetState,
643 : false,
644 : false,
645 : this.workflow,
646 : {
647 : checkForRerouteMigration: false,
648 : silentAssetErrors: true
649 : }
650 : )
651 76 : restored = result !== false && result !== undefined
652 : } finally {
653 76 : this._restoringState = false
654 76 : restored ||=
655 : !ChangeTracker.graphEqual(this.activeState, previousState) &&
656 : matchesRestoredTarget(this.activeState, targetState, previousState)
657 76 : if (restored) {
658 76 : target.push(previousState)
659 76 : if (restoresSavedState) this.initialState = clone(this.activeState)
660 : } else {
661 0 : source.push(prevState)
662 : }
663 76 : if (restored) {
664 76 : this.updateModified(previousState)
665 76 : forgetRemovedNodeHistories(
666 : collectNodeHistoryWidgets(useApp().rootGraph)
667 : )
668 : }
669 : }
670 : }
671 : }
672 82 : this.restoreChain = (this.restoreChain ?? Promise.resolve()).then(
673 : restore,
674 : restore
675 : )
676 82 : return this.restoreChain
677 : }
678 :
679 : async undo() {
680 57 : await this.updateState(this.undoQueue, this.redoQueue)
681 : }
682 :
683 : async redo() {
684 25 : await this.updateState(this.redoQueue, this.undoQueue)
685 : }
686 :
687 : async undoRedo(e: KeyboardEvent, selectOnly = isSelectOnly(useApp().canvas)) {
688 488 : const shortcut = historyShortcut(e)
689 488 : if (!shortcut) return
690 69 : if (!selectOnly) {
691 69 : await (shortcut === 'redo' ? this.redo() : this.undo())
692 : }
693 69 : return true
694 : }
695 :
696 : beforeChange() {
697 333 : this.changeCount++
698 : }
699 :
700 : afterChange() {
701 324 : if (!--this.changeCount) {
702 319 : this.captureCanvasState()
703 : }
704 : }
705 :
706 : static init() {
707 2355 : const getCurrentChangeTracker = () =>
708 : useWorkflowStore().activeWorkflow?.changeTracker
709 2355 : const captureState = () => getCurrentChangeTracker()?.captureCanvasState()
710 2355 : const dialogStore = useDialogStore()
711 :
712 2355 : let keyIgnored = false
713 2355 : window.addEventListener(
714 : 'keydown',
715 : (e: KeyboardEvent) => {
716 : // Do not trigger on repeat events (Holding down a key)
717 : // This can happen when user is holding down "Space" to pan the canvas.
718 1581 : if (e.repeat) return
719 :
720 : // If the mask editor is opened, we don't want to trigger on key events
721 1581 : if (clipspace.maskEditorIsOpened?.()) return
722 :
723 1581 : const activeEl = document.activeElement
724 1581 : if (
725 : !isAutoQueueOnChange() &&
726 : (activeEl?.tagName === 'INPUT' ||
727 : activeEl?.tagName === 'TEXTAREA' ||
728 : (activeEl instanceof HTMLElement && activeEl.isContentEditable))
729 : ) {
730 : // Text editors own their history. Bail out before the document-wide
731 : // modal probes, whose cost otherwise scales with transcript size.
732 573 : return
733 : }
734 1344 : if (isModalOpen(dialogStore.dialogStack.length)) return
735 :
736 : // The layer editor has its own session-local undo history
737 1068 : if (useDialogStore().isDialogOpen(LAYER_EDITOR_DIALOG_KEY)) return
738 :
739 973 : const shortcut = historyShortcut(e)
740 1581 : if (shortcut && travelFocusedNodeHistory(shortcut)) return
741 :
742 1581 : keyIgnored =
743 : e.key === 'Control' ||
744 : e.key === 'Shift' ||
745 : e.key === 'Alt' ||
746 : e.key === 'Meta'
747 1581 : if (keyIgnored) return
748 :
749 490 : const selectOnlyAtKeydown = isSelectOnly(useApp().canvas)
750 490 : requestAnimationFrame(async () => {
751 488 : let bindInputEl: Element | null = null
752 : // If we are auto queue in change mode then we do want to trigger on inputs
753 488 : if (!isAutoQueueOnChange()) {
754 487 : bindInputEl = activeEl
755 : }
756 :
757 488 : const changeTracker = getCurrentChangeTracker()
758 488 : if (!changeTracker) return
759 :
760 : // Check if this is a ctrl+z ctrl+y
761 488 : if (await changeTracker.undoRedo(e, selectOnlyAtKeydown)) return
762 :
763 : // If our active element is some type of input then handle changes after they're done
764 449 : if (ChangeTracker.bindInput(bindInputEl)) return
765 254 : changeTracker.captureCanvasState()
766 : })
767 : },
768 : true
769 : )
770 :
771 2355 : window.addEventListener('keyup', () => {
772 1558 : if (keyIgnored) {
773 195 : keyIgnored = false
774 195 : captureState()
775 : }
776 : })
777 :
778 2355 : window.addEventListener('mouseup', () => {
779 4481 : if (dialogStore.isDialogOpen(TEXT_EDITOR_DIALOG_KEY)) return
780 4479 : captureState()
781 : })
782 :
783 2355 : api.addEventListener('promptQueued', () => {
784 157 : captureState()
785 : })
786 :
787 2355 : api.addEventListener('graphCleared', () => {
788 88 : captureState()
789 : })
790 :
791 : // Handle litegraph clicks
792 2355 : const processMouseUp = LGraphCanvas.prototype.processMouseUp
793 2355 : LGraphCanvas.prototype.processMouseUp = function (e) {
794 1035 : const v = processMouseUp.apply(this, [e])
795 1035 : captureState()
796 1035 : return v
797 : }
798 :
799 : // Handle litegraph dialog popup for number/string widgets
800 2355 : const prompt = LGraphCanvas.prototype.prompt
801 2355 : LGraphCanvas.prototype.prompt = function (
802 : title: string,
803 : value: string | number,
804 : callback: (v: string) => void,
805 : event: CanvasPointerEvent
806 : ) {
807 29 : const extendedCallback = (v: string) => {
808 16 : callback(v)
809 16 : captureState()
810 : }
811 29 : return prompt.apply(this, [title, value, extendedCallback, event])
812 : }
813 :
814 : // Handle litegraph context menu for COMBO widgets
815 2355 : const close = LiteGraph.ContextMenu.prototype.close
816 2355 : LiteGraph.ContextMenu.prototype.close = function (e: MouseEvent) {
817 121 : const v = close.apply(this, [e])
818 121 : captureState()
819 121 : return v
820 : }
821 :
822 : // Handle multiple commands as a single transaction
823 2355 : document.addEventListener('litegraph:canvas', (e: Event) => {
824 818 : const detail = (e as CustomEvent).detail
825 818 : if (detail.subType === 'before-change') {
826 320 : getCurrentChangeTracker()?.beforeChange()
827 498 : } else if (detail.subType === 'after-change') {
828 311 : getCurrentChangeTracker()?.afterChange()
829 : }
830 : })
831 :
832 : // Store node outputs
833 2355 : api.addEventListener('executed', (e: CustomEvent<ExecutedWsMessage>) => {
834 155 : const detail = e.detail
835 : const workflow =
836 : useExecutionStore().queuedJobs[detail.prompt_id]?.workflow
837 155 : const changeTracker = workflow?.changeTracker
838 155 : if (!changeTracker) return
839 127 : changeTracker.nodeOutputs ??= {}
840 127 : const nodeOutputs = changeTracker.nodeOutputs
841 127 : const output = nodeOutputs[detail.node]
842 155 : if (detail.merge && output) {
843 0 : for (const k in detail.output) {
844 0 : const v = output[k]
845 0 : if (v instanceof Array) {
846 0 : output[k] = v.concat(detail.output[k])
847 : } else {
848 0 : output[k] = detail.output[k]
849 : }
850 : }
851 : } else {
852 127 : nodeOutputs[detail.node] = detail.output
853 : }
854 : })
855 : }
856 :
857 : static bindInput(activeEl: Element | null): boolean {
858 419 : if (
859 : !activeEl ||
860 : activeEl.tagName === 'CANVAS' ||
861 : activeEl.tagName === 'BODY'
862 : ) {
863 254 : return false
864 : }
865 :
866 165 : for (const evt of ['change', 'input', 'blur']) {
867 165 : const htmlElement = activeEl as HTMLElement
868 165 : if (`on${evt}` in htmlElement) {
869 165 : const listener = () => {
870 0 : useWorkflowStore().activeWorkflow?.changeTracker.captureCanvasState()
871 0 : htmlElement.removeEventListener(evt, listener)
872 : }
873 165 : htmlElement.addEventListener(evt, listener)
874 165 : return true
875 : }
876 : }
877 0 : return false
878 : }
879 :
880 : static graphEqual(
881 : a: ComfyWorkflowJSON | null | undefined,
882 : b: ComfyWorkflowJSON | null | undefined
883 : ) {
884 11484 : if (!a || !b) {
885 0 : reportWorkflowStateAnomaly(
886 : 'ChangeTracker.graphEqual() called with a missing state',
887 : 'ChangeTracker.graphEqual',
888 : undefined,
889 : { hasFirst: !!a, hasSecond: !!b }
890 : )
891 0 : return false
892 : }
893 11484 : if (a === b) return true
894 :
895 : // Compare nodes ignoring array position and execution order
896 11484 : if (
897 : !_.isEqualWith(
898 : withoutExecutionOrder(a.nodes),
899 : withoutExecutionOrder(b.nodes),
900 : (arrA, arrB) => {
901 11458 : if (Array.isArray(arrA) && Array.isArray(arrB)) {
902 11458 : return _.isEqual(new Set(arrA), new Set(arrB))
903 : }
904 : }
905 : )
906 : ) {
907 2451 : return false
908 : }
909 :
910 : // Compare extra properties ignoring ds
911 11484 : if (
912 : !_.isEqual(_.omit(a.extra ?? {}, ['ds']), _.omit(b.extra ?? {}, ['ds']))
913 : )
914 367 : return false
915 :
916 : // Compare other properties normally
917 11376 : for (const key of [
918 : 'links',
919 : 'floatingLinks',
920 : 'reroutes',
921 : 'groups',
922 : 'definitions',
923 : 'subgraphs'
924 : ]) {
925 51557 : if (!_.isEqual(a[key], b[key])) {
926 253 : return false
927 : }
928 : }
929 :
930 8387 : return true
931 : }
932 : }
933 :
934 2356 : provideChangeTracker(ChangeTracker)
|