Line data Source code
1 : /**
2 : * Mints the bound document's semantic operations from graph intents: the
3 : * commands litegraph announces at its own API funnels (`graphIntents.ts`),
4 : * each tagged with provenance. Only `local` intents mint; `load` and
5 : * `agent-remote` are skipped by that field, never inferred.
6 : *
7 : * Intents are collected synchronously and enqueued together at the end of
8 : * the tick, in command order. Only `add_node` reads anything at that point:
9 : * paste adds a node and then configures it, so the snapshot waits for the
10 : * command's own tick to finish. A node added and removed in one tick mints
11 : * nothing, and neither do the links it was wired with in between; a widget
12 : * write on a node whose add is still pending is already in that snapshot.
13 : */
14 : import type {
15 : NodeId as WireNodeId,
16 : PromotedHostWrite,
17 : SubgraphDefinition,
18 : WorkflowNode
19 : } from '@comfyorg/comfy-multi-player'
20 : import { isEqual } from 'es-toolkit'
21 :
22 : import { liveAutogrowGroupOf } from '@/core/graph/widgets/dynamicWidgets'
23 : import { registerDocBoundRootGraphProbe } from '@/lib/litegraph/src/docBoundGraphs'
24 : import { onGraphIntent } from '@/lib/litegraph/src/graphIntents'
25 : import type { GraphIntentEvent } from '@/lib/litegraph/src/graphIntents'
26 : import type { INodeInputSlot } from '@comfyorg/graph-model/slots'
27 : import type { LGraph } from '@/lib/litegraph/src/LGraph'
28 : import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
29 : import type { LLink } from '@/lib/litegraph/src/LLink'
30 : import type { Subgraph } from '@/lib/litegraph/src/subgraph/Subgraph'
31 : import type { SubgraphNode } from '@/lib/litegraph/src/subgraph/SubgraphNode'
32 : import type { ISerialisedNode } from '@comfyorg/graph-model/serialisation'
33 : import { isWidgetValue } from '@comfyorg/graph-model/widgets'
34 : import { reportError } from '@comfyorg/telemetry/reportError'
35 : import { useNodeDefStore } from '@/stores/nodeDefStore'
36 : import type { DynamicComboSelection } from '@/stores/nodeDefStore'
37 : import { useWidgetValueStore } from '@/stores/widgetValueStore'
38 : import type { RootGraphId } from '@comfyorg/graph-model/graphScopeId'
39 : import type { NodeId } from '@comfyorg/graph-model/nodeId'
40 : import { widgetId } from '@comfyorg/graph-model/widgetId'
41 : import {
42 : findNodeInHierarchy,
43 : findSubgraphByUuid,
44 : findSubgraphNodePathById,
45 : traverseSubgraphPath
46 : } from '@/utils/graphTraversalUtil'
47 :
48 : import {
49 : SUBSCRIBE_ACK_MAX_TIMEOUTS,
50 : SUBSCRIBE_ACK_TIMEOUT_MS
51 : } from './agentCrdtDocLifecycle'
52 : import type { GraphOperation } from './graphOperations'
53 : import type { DocPromotedWidgets } from './agentSubgraphDefinitions'
54 : import { reportLostEdit } from './reportLostEdit'
55 : import {
56 : isValueWidget,
57 : provenWidgetValuesForm,
58 : valueWidgetsOnly
59 : } from './widgetValuesForm'
60 :
61 : export interface DocOpMinterDeps {
62 : /** Slice 00's product gate. */
63 : isEnabled(): boolean
64 : /** A semantic doc is bound for the active workflow. */
65 : isDocBound(): boolean
66 : /** Records a local edit that cannot yet enter the semantic document. */
67 : onUnboundLocalIntent?(): void
68 : /** Records a local edit to the visible workflow while another one, or none, is bound. */
69 : onUnboundVisibleIntent?(): void
70 : /** Receives minted semantic operations (the sender's inbox). */
71 : enqueue(operations: GraphOperation[]): void
72 : /** The live root graph, or null when no workflow is open. */
73 : getGraph(): LGraph | null
74 : /**
75 : * The bound workflow's own stored root graph id, or null when no workflow
76 : * is bound. Read from the workflow's serialized state rather than the live
77 : * canvas graph, so it names the bound document's graph even while a tab
78 : * switch is loading another workflow into the shared canvas graph.
79 : */
80 : boundRootGraphId(): RootGraphId | null
81 : /**
82 : * The bound document's input slot names for a node, in document order, or
83 : * null when the document holds no such node (its `add_node` is still in
84 : * flight, or no document is subscribed).
85 : */
86 : docInputNames(nodeId: NodeId): readonly (string | undefined)[] | null
87 : /**
88 : * The bound document's value for a node's widget. The dynamic-combo
89 : * selection gate cannot tell a stale document from one that lacks the
90 : * widget without it, so every caller supplies it.
91 : */
92 : docWidgetValue(nodeId: NodeId, widgetName: string): unknown
93 : /**
94 : * The bound document's view of a node's promoted widget layout, or null
95 : * when the document holds no such node.
96 : */
97 : docPromotedWidgets(nodeId: NodeId): DocPromotedWidgets | null
98 : /**
99 : * False until the bound document has caught up, unless this tab already
100 : * sent the root host's `add_node` into the same document. Every resubscribe
101 : * (stale probe, reconnect, gap resync, ack-timeout retry) makes it false
102 : * again until its catch-up lands, so a false answer holds the write (see
103 : * {@link PROMOTED_WRITE_CATCH_UP_DEADLINE_MS}) rather than refusing it.
104 : */
105 : mayWritePromotedHost(nodeId: NodeId): boolean
106 : /** Whether the bound document holds a subgraph definition by this id. */
107 : docHasSubgraphDefinition(definitionId: string): boolean
108 : onWidgetWriteRefused(nodeId: NodeId, widgetName: string): void
109 : }
110 :
111 : /**
112 : * How long a promoted-host write waits for the bound document to catch up
113 : * before it is refused: as long as the subscribe lifecycle keeps retrying.
114 : */
115 2355 : export const PROMOTED_WRITE_CATCH_UP_DEADLINE_MS =
116 : SUBSCRIBE_ACK_MAX_TIMEOUTS * SUBSCRIBE_ACK_TIMEOUT_MS
117 : /** How often a held promoted-host write rechecks the catch-up gate. */
118 : export const PROMOTED_WRITE_RETRY_MS = 100
119 :
120 : type PromotedWriteRefusal =
121 : | { reason: 'unpromoted_widget'; liveNames: readonly string[] }
122 : | { reason: 'doc_not_synced' }
123 : | { reason: 'workflow_changed' }
124 : | {
125 : reason: 'layout_drift'
126 : liveNames: readonly string[]
127 : doc: DocPromotedWidgets
128 : }
129 :
130 : export interface DocOpMinter {
131 : detach(): void
132 : }
133 :
134 : type IntentOf<T extends GraphIntentEvent['type']> = Extract<
135 : GraphIntentEvent,
136 : { type: T }
137 : >
138 :
139 : interface HeldPromotedWrite {
140 : event: IntentOf<'set_widget'>
141 : rootGraphId: string
142 : heldSince: number
143 : }
144 :
145 0 : function heldWriteKey(event: IntentOf<'set_widget'>): string {
146 0 : return JSON.stringify([event.graphId, String(event.nodeId), event.name])
147 : }
148 :
149 : type PendingOp =
150 : | { kind: 'add_node'; graph: LGraph; node: LGraphNode }
151 : | { kind: 'op'; operation: GraphOperation }
152 :
153 : interface DeferredDynamicConnect {
154 : kind: 'connect'
155 : operation: Omit<
156 : Extract<GraphOperation, { op: 'connect'; to_slot: number }>,
157 : 'to_slot' | 'grow'
158 : >
159 : }
160 :
161 : interface DeferredDynamicDisconnect {
162 : kind: 'disconnect'
163 : operation: Omit<Extract<GraphOperation, { op: 'disconnect' }>, 'to_slot'>
164 : }
165 :
166 : type DeferredDynamicOperation =
167 : | DeferredDynamicConnect
168 : | DeferredDynamicDisconnect
169 :
170 : interface PendingDynamicSlot {
171 : /**
172 : * The root graph the grow was minted against. A delayed operation may only
173 : * ever reach that document: CRDT-WRITE-0035 lets a batch wait, never be
174 : * re-addressed.
175 : */
176 : rootGraphId: string
177 : nodeId: NodeId
178 : inputName: string
179 : growLinkId: WireNodeId
180 : since: number
181 : sent: boolean
182 : deferred: DeferredDynamicOperation[]
183 : }
184 :
185 : interface PendingWidgetValue {
186 : nodeId: NodeId
187 : widgetName: string
188 : value: unknown
189 : documentValueAtWrite: unknown
190 : }
191 :
192 : type MissingSlotGrowth = NonNullable<ReturnType<typeof growForMissingSlot>>
193 :
194 : /**
195 : * Returns the node's save-format snapshot for a semantic add operation.
196 : *
197 : * Excludes only subgraph hosts, whose widget values are positional by design
198 : * (`applyHostWidgets` indexes them against the live promoted inputs). Every
199 : * other named-value node gets a declared `widgets_values_form` when one can
200 : * be proven (schema A24); otherwise it keeps the positional snapshot rather
201 : * than shipping an undeclared name-keyed record (KA-12).
202 : */
203 0 : export function wireNodeSnapshot(node: LGraphNode): WorkflowNode | null {
204 0 : let serialized: ISerialisedNode
205 0 : try {
206 0 : serialized = node.serialize()
207 : } catch {
208 0 : return null
209 : }
210 0 : const wireSerialized = { ...serialized }
211 0 : Reflect.deleteProperty(wireSerialized, '__incarnation')
212 0 : Reflect.deleteProperty(wireSerialized, 'widgets_values_form')
213 0 : const {
214 : widgets_values_named: named,
215 : flags: { ghost: _ghost, ...flags },
216 : ...rest
217 : } = wireSerialized
218 0 : const snapshot = { ...rest, flags } satisfies WorkflowNode
219 0 : if (!named || node.isSubgraphNode()) return snapshot
220 0 : const values = valueWidgetsOnly(node, named)
221 0 : const form = provenWidgetValuesForm(node, values, serialized)
222 0 : if (form)
223 0 : return { ...snapshot, widgets_values: values, widgets_values_form: form }
224 0 : return node.isVirtualNode ? snapshot : { ...snapshot, widgets_values: values }
225 : }
226 :
227 0 : function nodeKey(graphId: string, nodeId: NodeId): string {
228 0 : return `${graphId}:${String(nodeId)}`
229 : }
230 :
231 0 : function reachableIntentGraph(
232 : graph: LGraph,
233 : graphId: string
234 : ): LGraph | Subgraph | null {
235 0 : if (graphId === graph.id) return graph
236 0 : const registered = findSubgraphByUuid(graph, graphId)
237 0 : if (registered) return registered
238 0 : const path = findSubgraphNodePathById(graph, graphId)
239 0 : return path ? traverseSubgraphPath(graph, path) : null
240 : }
241 :
242 : /**
243 : * Whether the live widget, or the store metadata the intent was keyed by when
244 : * the live widget is missing or omits a field, identifies a value the document
245 : * carries. Unknown widgets fail closed.
246 : */
247 0 : function isValueWidgetWrite(
248 : owner: LGraphNode | null,
249 : event: IntentOf<'set_widget'>
250 : ): boolean {
251 0 : const rootGraphId = owner?.graph?.rootGraph.id ?? event.graphId
252 0 : const stored = useWidgetValueStore().getWidget(
253 : widgetId(rootGraphId, event.nodeId, event.name)
254 : )
255 0 : const widget = owner?.widgets?.find(
256 : (candidate) => candidate.name === event.name
257 : )
258 0 : return isValueWidget(widget, stored)
259 : }
260 :
261 0 : function promotedHostWrite(
262 : node: LGraphNode,
263 : event: IntentOf<'set_widget'>,
264 : deps: Pick<DocOpMinterDeps, 'docPromotedWidgets' | 'mayWritePromotedHost'>
265 : ): PromotedHostWrite | PromotedWriteRefusal {
266 0 : const hostInputs = node.inputs.flatMap((input) =>
267 : input.widgetId ? [{ name: input.name, widgetId: input.widgetId }] : []
268 : )
269 0 : const valueIndex = hostInputs.findIndex((input) => input.name === event.name)
270 0 : const liveNames = hostInputs.map((input) => input.name)
271 0 : if (valueIndex === -1) return { reason: 'unpromoted_widget', liveNames }
272 0 : if (!deps.mayWritePromotedHost(event.nodeId))
273 0 : return { reason: 'doc_not_synced' }
274 0 : const doc = deps.docPromotedWidgets(event.nodeId)
275 0 : if (doc !== null && !documentAcceptsLiveIndex(doc, liveNames))
276 0 : return { reason: 'layout_drift', liveNames, doc }
277 0 : const widgetValueStore = useWidgetValueStore()
278 0 : return {
279 : value_index: valueIndex,
280 : instance_path: [String(event.nodeId)],
281 : host_widgets_values: hostInputs.map((input, index) => {
282 0 : if (index === valueIndex) return undefined
283 0 : const value = widgetValueStore.getWidget(input.widgetId)?.value
284 0 : return isWidgetValue(value) ? value : undefined
285 : })
286 : }
287 : }
288 :
289 : /**
290 : * Whether a live index is a safe index into the document's array.
291 : *
292 : * Two independent ways it is not, and the document answers both:
293 : *
294 : * - The array is sized for a different set of widgets. Checked against
295 : * `valueCount`, the same cardinality invariant `applyHostWidgets` enforces
296 : * on the way in.
297 : * - The promoted name sequence is different. Definition order combined with
298 : * the instance's stored input mirror identifies the exact names behind the
299 : * positional array, catching same-cardinality demote/promote swaps as well
300 : * as `reorderSubgraphInputsByWidgetOrder` permutations.
301 : *
302 : * A document holding no array yet is sized by nothing, but it is NOT ordered
303 : * by nothing: the first write seeds the whole array from `host_widgets_values`
304 : * in live order, and a reload reads it back in the DEFINITION's order
305 : * (`_applyPromotedWidgetValues`). A reorder permutes the live definition
306 : * without minting, so the document's copy still holds the old order — seeding
307 : * against it would land every value on a neighbour. Only a document that
308 : * declares no definition at all leaves the live order unopposed.
309 : *
310 : * A refused write is dropped before enqueue so its `opaque_widgets` rejection
311 : * cannot abort unrelated operations in the same batch.
312 : */
313 0 : function documentAcceptsLiveIndex(
314 : doc: DocPromotedWidgets | null,
315 : liveNames: readonly string[]
316 : ): boolean {
317 0 : if (doc === null) return true
318 0 : const namesMatch =
319 : doc.promotedNames != null &&
320 : doc.promotedNames.length === liveNames.length &&
321 : doc.promotedNames.every((name, index) => name === liveNames[index])
322 0 : if (doc.valueCount === 0) return doc.promotedNames === undefined || namesMatch
323 0 : return doc.valueCount === liveNames.length && namesMatch
324 : }
325 :
326 0 : function routedWidgetOperation(
327 : graph: LGraph,
328 : rootGraphId: string,
329 : event: IntentOf<'set_widget'>,
330 : node: LGraphNode | null,
331 : deps: Pick<DocOpMinterDeps, 'docPromotedWidgets' | 'mayWritePromotedHost'>
332 : ): GraphOperation | PromotedWriteRefusal | { unresolvedGraphId: string } {
333 0 : const operation = {
334 : op: 'set_widget',
335 : node_id: event.nodeId,
336 : widget: event.name,
337 : value: event.value
338 : } as const
339 0 : const owningGraphId = node?.graph?.id ?? event.graphId
340 0 : if (owningGraphId === rootGraphId) {
341 0 : if (!node?.isSubgraphNode()) return operation
342 0 : const promoted = promotedHostWrite(node, event, deps)
343 0 : return 'reason' in promoted ? promoted : { ...operation, promoted }
344 : }
345 0 : const subgraphNodePath = findSubgraphNodePathById(graph, owningGraphId)
346 0 : if (subgraphNodePath === null || subgraphNodePath.length === 0)
347 0 : return { unresolvedGraphId: owningGraphId }
348 0 : const [head, ...rest] = subgraphNodePath
349 0 : return {
350 : ...operation,
351 : path: [head, ...rest, String(event.nodeId)],
352 : inner_widget: event.name
353 : }
354 : }
355 :
356 : /**
357 : * Drops a same-tick pending `add_node` together with every link command that
358 : * touched it: the doc never sees the node, so a `connect` naming it would
359 : * dangle, and a `disconnect` of such a link would target a link the doc
360 : * never had.
361 : */
362 0 : function withoutCancelledAdd(
363 : pending: PendingOp[],
364 : nodeId: NodeId
365 : ): PendingOp[] {
366 0 : const cancelledLinkIds = new Set<WireNodeId>()
367 0 : for (const entry of pending) {
368 0 : if (entry.kind !== 'op' || entry.operation.op !== 'connect') continue
369 0 : const { from_node, to_node, link_id } = entry.operation
370 0 : if (from_node === nodeId || to_node === nodeId)
371 0 : cancelledLinkIds.add(link_id)
372 : }
373 0 : return pending.filter((entry) => {
374 0 : if (entry.kind === 'add_node') return entry.node.id !== nodeId
375 0 : const { operation } = entry
376 0 : switch (operation.op) {
377 : case 'connect':
378 0 : return !cancelledLinkIds.has(operation.link_id)
379 : case 'disconnect':
380 0 : return (
381 : operation.to_node !== nodeId &&
382 : !cancelledLinkIds.has(operation.link_id)
383 : )
384 : default:
385 0 : return true
386 : }
387 : })
388 : }
389 :
390 : /**
391 : * The document input register a live link's target slot names, resolved by
392 : * NAME against the bound document's own input order: the live order drifts
393 : * from it (an autogrow slot disconnected and regrown lands at the tail of
394 : * its group live, while the document keeps its order), and the applier
395 : * indexes the document's array. The live index stands in only while the
396 : * document has no such node yet. Undefined when the document has the node
397 : * but no slot by that name.
398 : */
399 0 : export function docInputIndex(
400 : docNames: readonly (string | undefined)[] | null,
401 : input: Pick<INodeInputSlot, 'name'> | undefined,
402 : liveIndex: number
403 : ): number | undefined {
404 0 : if (docNames === null || input === undefined) return liveIndex
405 0 : const index = docNames.indexOf(input.name)
406 0 : return index === -1 ? undefined : index
407 : }
408 :
409 0 : function growForMissingSlot(
410 : target: LGraphNode | null | undefined,
411 : input: INodeInputSlot | undefined
412 : ):
413 : | {
414 : grow: { name: string; type: string; widget?: string }
415 : selection?: DynamicComboSelection
416 : }
417 : | undefined {
418 0 : if (!target || !input) return undefined
419 0 : const widgetBacked = !!input.widget && !target.isSubgraphNode()
420 0 : const autogrow = !!liveAutogrowGroupOf(target, input.name)
421 0 : const selection = useNodeDefStore().getDynamicComboSelectionForInput(
422 : target,
423 : input.name
424 : )
425 0 : if (!widgetBacked && !autogrow && !selection) return undefined
426 0 : return {
427 : grow: {
428 : name: input.name,
429 : type: String(input.type),
430 : ...(input.widget ? { widget: input.widget.name } : {})
431 : },
432 : ...(selection ? { selection } : {})
433 : }
434 : }
435 :
436 0 : function canvasReplaced(graph: LGraph, event: IntentOf<'set_widget'>): boolean {
437 0 : const eventGraph = reachableIntentGraph(graph, event.graphId)
438 : const host = eventGraph ? findNodeInHierarchy(eventGraph, event.nodeId) : null
439 0 : const input = host?.inputs.find((slot) => slot.name === event.name)
440 0 : const stored = input?.widgetId
441 : ? useWidgetValueStore().getWidget(input.widgetId)
442 : : undefined
443 0 : return stored !== undefined && !isEqual(stored.value, event.value)
444 : }
445 :
446 1 : export function attachDocOpMinter(deps: DocOpMinterDeps): DocOpMinter {
447 1 : let pending: PendingOp[] = []
448 1 : const pendingAdds = new Map<string, LGraphNode>()
449 1 : const pendingDynamicSlots = new Map<string, PendingDynamicSlot>()
450 1 : const pendingWidgetValues = new Map<string, PendingWidgetValue>()
451 1 : const reported = new Set<string>()
452 1 : const reportedRefusals = new Set<string>()
453 1 : const heldPromotedWrites = new Map<string, HeldPromotedWrite>()
454 1 : let heldRetryTimer: ReturnType<typeof setTimeout> | null = null
455 1 : let dynamicSlotRetryTimer: ReturnType<typeof setTimeout> | null = null
456 1 : let flushScheduled = false
457 1 : let detached = false
458 :
459 : /**
460 : * Scopes a pending slot to the document it was grown in, so a delayed
461 : * operation can never be found — and replayed — under another one.
462 : */
463 0 : function dynamicSlotKey(
464 : rootGraphId: string,
465 : nodeId: NodeId,
466 : inputName: string
467 : ): string {
468 0 : return JSON.stringify([rootGraphId, String(nodeId), inputName])
469 : }
470 :
471 0 : function widgetValueKey(nodeId: NodeId, widgetName: string): string {
472 0 : return JSON.stringify([String(nodeId), widgetName])
473 : }
474 :
475 : /**
476 : * True while the document still reads what it read when the write was
477 : * minted, which is the only state in which that write can still be the
478 : * next one to land. A document that reflects the written value has settled
479 : * it; any other value superseded it.
480 : */
481 0 : function widgetWriteInFlight(pending: PendingWidgetValue): boolean {
482 0 : const documentValue = deps.docWidgetValue(
483 : pending.nodeId,
484 : pending.widgetName
485 : )
486 0 : return (
487 : isEqual(documentValue, pending.documentValueAtWrite) &&
488 : !isEqual(documentValue, pending.value)
489 : )
490 : }
491 :
492 : /** Drops recorded writes the document has settled or superseded. */
493 0 : function retireSettledWidgetValues(): void {
494 0 : for (const [key, pending] of pendingWidgetValues)
495 0 : if (!widgetWriteInFlight(pending)) pendingWidgetValues.delete(key)
496 : }
497 :
498 : /**
499 : * Whether the bound document will carry this selector value by the time the
500 : * grow lands. An in-flight selector write decides it, because that write is
501 : * what the document reads next; otherwise the document's own value does.
502 : */
503 0 : function documentMatchesSelection(
504 : nodeId: NodeId,
505 : selection: DynamicComboSelection
506 : ): boolean {
507 0 : const key = widgetValueKey(nodeId, selection.widget)
508 0 : const pending = pendingWidgetValues.get(key)
509 0 : if (pending && !widgetWriteInFlight(pending))
510 0 : pendingWidgetValues.delete(key)
511 0 : const inFlight = pendingWidgetValues.get(key)
512 0 : if (inFlight) return isEqual(inFlight.value, selection.value)
513 0 : return isEqual(
514 : deps.docWidgetValue(nodeId, selection.widget),
515 : selection.value
516 : )
517 : }
518 :
519 0 : function resolvedDynamicSlot(state: PendingDynamicSlot): number | undefined {
520 : const names = deps.docInputNames(state.nodeId)
521 0 : const index = names?.indexOf(state.inputName) ?? -1
522 0 : return index < 0 ? undefined : index
523 : }
524 :
525 0 : function scheduleDeferredDynamicOperation(
526 : deferred: DeferredDynamicOperation,
527 : toSlot: number
528 : ): void {
529 0 : schedule({
530 : kind: 'op',
531 : operation: { ...deferred.operation, to_slot: toSlot }
532 : })
533 : }
534 :
535 0 : function releaseDynamicSlot(state: PendingDynamicSlot): boolean {
536 0 : const toSlot = resolvedDynamicSlot(state)
537 0 : if (toSlot === undefined) return false
538 0 : pendingDynamicSlots.delete(pendingSlotKey(state))
539 0 : for (const deferred of state.deferred)
540 0 : scheduleDeferredDynamicOperation(deferred, toSlot)
541 0 : return true
542 : }
543 :
544 0 : function pendingSlotKey(state: PendingDynamicSlot): string {
545 0 : return dynamicSlotKey(state.rootGraphId, state.nodeId, state.inputName)
546 : }
547 :
548 : /**
549 : * Drops a pending slot whose document is no longer bound, so its deferred
550 : * operations are never re-addressed to the document that replaced it.
551 : */
552 0 : function dropRetargetedDynamicSlot(state: PendingDynamicSlot): boolean {
553 0 : const boundRootGraphId =
554 : deps.boundRootGraphId() ?? deps.getGraph()?.rootGraph.id ?? null
555 0 : if (boundRootGraphId === null || boundRootGraphId === state.rootGraphId)
556 0 : return false
557 0 : const key = pendingSlotKey(state)
558 0 : pendingDynamicSlots.delete(key)
559 0 : reportOnce(
560 : `dynamic_slot_workflow_changed:${key}`,
561 : `Dynamic-combo input ${state.inputName} of node ${String(state.nodeId)} belongs to graph ${state.rootGraphId}, which is no longer bound; dropping its deferred link operations rather than replaying them into ${boundRootGraphId}`,
562 : 'agent_crdt_link_slot_workflow_changed',
563 : {
564 : nodeId: state.nodeId,
565 : input: state.inputName,
566 : rootGraphId: state.rootGraphId,
567 : boundRootGraphId,
568 : operations: state.deferred.map(({ kind }) => kind)
569 : }
570 : )
571 0 : return true
572 : }
573 :
574 0 : function dropExpiredDynamicSlot(state: PendingDynamicSlot): boolean {
575 0 : if (performance.now() - state.since < PROMOTED_WRITE_CATCH_UP_DEADLINE_MS)
576 0 : return false
577 0 : const key = pendingSlotKey(state)
578 0 : pendingDynamicSlots.delete(key)
579 0 : reportOnce(
580 : `dynamic_slot_timeout:${key}`,
581 : `Dynamic-combo input ${state.inputName} of node ${String(state.nodeId)} never reached the bound document; dropping its deferred link operations`,
582 : 'agent_crdt_link_slot_not_in_doc',
583 : {
584 : nodeId: state.nodeId,
585 : input: state.inputName,
586 : operations: state.deferred.map(({ kind }) => kind)
587 : }
588 : )
589 0 : return true
590 : }
591 :
592 0 : function retryDynamicSlots(): void {
593 0 : dynamicSlotRetryTimer = null
594 0 : if (detached) return
595 0 : let waiting = false
596 0 : for (const state of pendingDynamicSlots.values()) {
597 0 : if (dropRetargetedDynamicSlot(state)) continue
598 0 : if (releaseDynamicSlot(state) || dropExpiredDynamicSlot(state)) continue
599 0 : waiting = true
600 : }
601 0 : if (waiting)
602 0 : dynamicSlotRetryTimer = setTimeout(
603 : retryDynamicSlots,
604 : PROMOTED_WRITE_RETRY_MS
605 : )
606 : }
607 :
608 0 : function retryDynamicSlotsSoon(): void {
609 0 : if (dynamicSlotRetryTimer !== null) return
610 0 : dynamicSlotRetryTimer = setTimeout(
611 : retryDynamicSlots,
612 : PROMOTED_WRITE_RETRY_MS
613 : )
614 : }
615 :
616 0 : function schedule(op: PendingOp): void {
617 0 : pending.push(op)
618 0 : if (flushScheduled) return
619 0 : flushScheduled = true
620 0 : queueMicrotask(flush)
621 : }
622 :
623 0 : function mintAddNodeOperation(
624 : graph: LGraph,
625 : node: LGraphNode
626 : ): GraphOperation | null {
627 0 : if (node.graph !== graph) return null
628 0 : const snapshot = wireNodeSnapshot(node)
629 0 : if (!snapshot) {
630 0 : const key = `snapshot:${nodeKey(graph.id, node.id)}`
631 0 : if (reported.has(key)) return null
632 0 : reported.add(key)
633 0 : reportLostEdit('mint_divergence', [{ op: 'add_node' }], {
634 : code: 'missing_node_snapshot',
635 : errorType: 'agent_crdt_node_snapshot_missing',
636 : graphId: graph.id,
637 : nodeId: node.id
638 : })
639 0 : return null
640 : }
641 0 : return {
642 : op: 'add_node',
643 : node_id: node.id,
644 : class_type: snapshot.type,
645 : pos: [node.pos[0], node.pos[1]],
646 : node: snapshot
647 : }
648 : }
649 :
650 0 : function serialisedDefinition(subgraph: Subgraph): SubgraphDefinition | null {
651 0 : try {
652 0 : return JSON.parse(JSON.stringify(subgraph.asSerialisable()))
653 : } catch (error) {
654 0 : reportError(error, {
655 : surface: 'agent',
656 : errorType: 'agent_crdt_subgraph_definition_unserializable',
657 : context: { definitionId: subgraph.id }
658 : })
659 0 : return null
660 : }
661 : }
662 :
663 0 : function mintMissingDefinitions(
664 : hosts: readonly SubgraphNode[]
665 : ): GraphOperation[] {
666 0 : const operations: GraphOperation[] = []
667 0 : const available = new Map<string, boolean>()
668 0 : const define = (subgraph: Subgraph): boolean => {
669 0 : const settled = available.get(subgraph.id)
670 0 : if (settled !== undefined) return settled
671 0 : available.set(subgraph.id, false)
672 0 : const dependenciesAvailable = subgraph.nodes
673 : .filter((node) => node.isSubgraphNode())
674 : .map((node) => define(node.subgraph))
675 : .every(Boolean)
676 0 : if (deps.docHasSubgraphDefinition(subgraph.id)) {
677 0 : available.set(subgraph.id, true)
678 0 : return true
679 : }
680 0 : const definition = dependenciesAvailable
681 : ? serialisedDefinition(subgraph)
682 : : null
683 0 : if (!definition) return false
684 0 : operations.push({
685 : op: 'define_subgraph',
686 : subgraph_id: subgraph.id,
687 : subgraph_definition: definition
688 : })
689 0 : available.set(subgraph.id, true)
690 0 : return true
691 : }
692 0 : for (const host of hosts) define(host.subgraph)
693 0 : return operations
694 : }
695 :
696 0 : function flush(): void {
697 0 : flushScheduled = false
698 0 : reported.clear()
699 0 : const batch = pending
700 0 : pending = []
701 0 : pendingAdds.clear()
702 0 : if (detached) return
703 0 : const hosts: SubgraphNode[] = []
704 0 : const operations = batch.flatMap((entry) => {
705 0 : if (entry.kind === 'op') return [entry.operation]
706 0 : const operation = mintAddNodeOperation(entry.graph, entry.node)
707 0 : if (!operation) return []
708 0 : if (entry.node.isSubgraphNode()) hosts.push(entry.node)
709 0 : return [operation]
710 : })
711 0 : operations.push(...mintMissingDefinitions(hosts))
712 0 : for (const state of pendingDynamicSlots.values()) {
713 0 : if (state.sent) continue
714 0 : state.sent = operations.some(
715 : (operation) =>
716 : operation.op === 'connect' &&
717 : operation.link_id === state.growLinkId &&
718 : 'grow' in operation
719 : )
720 : }
721 0 : if (operations.length > 0) deps.enqueue(operations)
722 : }
723 :
724 0 : function reportOnce(
725 : key: string,
726 : message: string,
727 : errorType: string,
728 : context: Record<string, unknown>,
729 : budget: Set<string> = reported
730 : ): void {
731 0 : if (budget.has(key)) return
732 0 : budget.add(key)
733 0 : reportError(new Error(message), { surface: 'agent', errorType, context })
734 : }
735 :
736 : /** True when `graph` is the bound document's root graph. */
737 0 : function isMintableRootScope(
738 : graph: LGraph,
739 : action: string,
740 : entityId: NodeId | string | number
741 : ): boolean {
742 0 : const boundRootGraphId = deps.boundRootGraphId()
743 0 : const rootGraphId = graph.rootGraph.id
744 0 : if (boundRootGraphId !== null && rootGraphId !== boundRootGraphId) {
745 0 : reportOnce(
746 : `${action}:${rootGraphId}:${boundRootGraphId}`,
747 : `${action} targets graph ${rootGraphId}, not the bound document's root graph ${boundRootGraphId}; refusing to mint`,
748 : 'agent_crdt_op_for_unbound_graph',
749 : { graphId: rootGraphId, boundRootGraphId, entityId }
750 : )
751 0 : return false
752 : }
753 0 : if (!graph.isRootGraph) {
754 0 : reportOnce(
755 : `${action}:${graph.id}:interior`,
756 : `Subgraph-interior ${action} has no wire op; the bound doc diverges from the local graph`,
757 : `agent_crdt_unrepresentable_subgraph_${action}`,
758 : { graphId: rootGraphId, ownerGraphId: graph.id, entityId }
759 : )
760 0 : return false
761 : }
762 0 : return true
763 : }
764 :
765 0 : function routeSetWidget(
766 : event: IntentOf<'set_widget'>,
767 : retried: HeldPromotedWrite | null
768 : ): void {
769 0 : const held = retried ?? takeHeldWrite(event)
770 0 : if (pendingAdds.has(nodeKey(event.graphId, event.nodeId))) return
771 0 : const graph = deps.getGraph()
772 0 : if (!graph) return
773 0 : const eventGraph = reachableIntentGraph(graph, event.graphId)
774 0 : const owner = eventGraph
775 : ? findNodeInHierarchy(eventGraph, event.nodeId)
776 : : null
777 0 : if (!isValueWidgetWrite(owner, event)) return
778 0 : const rootGraphId = deps.boundRootGraphId() ?? graph.id
779 0 : const routed = routedWidgetOperation(graph, rootGraphId, event, owner, deps)
780 0 : if ('unresolvedGraphId' in routed) {
781 0 : reportUnresolvedWidgetOwner(routed.unresolvedGraphId, event)
782 0 : return
783 : }
784 0 : if ('reason' in routed) {
785 0 : holdOrRefuseWidgetWrite(rootGraphId, event, routed, held)
786 0 : return
787 : }
788 0 : rememberPendingWidgetValue(routed, event)
789 0 : schedule({ kind: 'op', operation: routed })
790 : }
791 :
792 0 : function rememberPendingWidgetValue(
793 : operation: GraphOperation,
794 : event: IntentOf<'set_widget'>
795 : ): void {
796 0 : if (
797 : operation.op !== 'set_widget' ||
798 : 'path' in operation ||
799 : 'promoted' in operation
800 : )
801 0 : return
802 0 : retireSettledWidgetValues()
803 0 : pendingWidgetValues.set(widgetValueKey(event.nodeId, event.name), {
804 : nodeId: event.nodeId,
805 : widgetName: event.name,
806 : value: event.value,
807 : documentValueAtWrite: deps.docWidgetValue(event.nodeId, event.name)
808 : })
809 : }
810 :
811 0 : function reportUnresolvedWidgetOwner(
812 : graphId: string,
813 : event: IntentOf<'set_widget'>
814 : ): void {
815 0 : const key = `owner:${nodeKey(graphId, event.nodeId)}:${event.name}`
816 0 : if (reportedRefusals.has(key)) return
817 0 : reportedRefusals.add(key)
818 0 : reportLostEdit('mint_divergence', [{ op: 'set_widget' }], {
819 : code: 'unresolvable_widget_owner',
820 : errorType: 'agent_crdt_widget_owner_unresolved',
821 : graphId,
822 : nodeId: event.nodeId,
823 : widget: event.name
824 : })
825 : }
826 :
827 0 : function takeHeldWrite(
828 : event: IntentOf<'set_widget'>
829 : ): HeldPromotedWrite | null {
830 0 : const key = heldWriteKey(event)
831 0 : const held = heldPromotedWrites.get(key) ?? null
832 0 : heldPromotedWrites.delete(key)
833 0 : return held
834 : }
835 :
836 0 : function holdOrRefuseWidgetWrite(
837 : rootGraphId: string,
838 : event: IntentOf<'set_widget'>,
839 : refusal: PromotedWriteRefusal,
840 : held: HeldPromotedWrite | null
841 : ): void {
842 0 : const heldSince = held?.heldSince ?? performance.now()
843 : const mayWait =
844 : refusal.reason === 'doc_not_synced' &&
845 : performance.now() - heldSince < PROMOTED_WRITE_CATCH_UP_DEADLINE_MS
846 0 : if (mayWait) holdPromotedWrite({ event, rootGraphId, heldSince })
847 0 : else refuseWidgetWrite(rootGraphId, event, refusal)
848 : }
849 :
850 0 : function refuseWidgetWrite(
851 : rootGraphId: string,
852 : event: IntentOf<'set_widget'>,
853 : refusal: PromotedWriteRefusal
854 : ): void {
855 0 : reportRefusal(rootGraphId, event, refusal)
856 0 : deps.onWidgetWriteRefused(event.nodeId, event.name)
857 : }
858 :
859 0 : function holdPromotedWrite(held: HeldPromotedWrite): void {
860 0 : heldPromotedWrites.set(heldWriteKey(held.event), held)
861 0 : if (heldRetryTimer !== null) return
862 0 : heldRetryTimer = setTimeout(
863 : retryHeldPromotedWrites,
864 : PROMOTED_WRITE_RETRY_MS
865 : )
866 : }
867 :
868 0 : function retryHeldPromotedWrites(): void {
869 0 : heldRetryTimer = null
870 0 : if (detached) return
871 0 : const held = [...heldPromotedWrites.values()]
872 0 : heldPromotedWrites.clear()
873 0 : const bound = deps.isDocBound()
874 0 : if (!deps.isEnabled() || (!bound && deps.boundRootGraphId() === null))
875 0 : return
876 0 : const graph = bound ? deps.getGraph() : null
877 0 : for (const entry of held) {
878 0 : if (graph) retryHeldWrite(graph, entry)
879 0 : else waitOrGiveUp(entry)
880 : }
881 : }
882 :
883 0 : function waitOrGiveUp(entry: HeldPromotedWrite): void {
884 0 : if (!heldTooLong(entry)) holdPromotedWrite(entry)
885 : else
886 0 : refuseWidgetWrite(entry.rootGraphId, entry.event, {
887 : reason: 'doc_not_synced'
888 : })
889 : }
890 :
891 0 : function heldTooLong(entry: HeldPromotedWrite): boolean {
892 0 : return (
893 : performance.now() - entry.heldSince >= PROMOTED_WRITE_CATCH_UP_DEADLINE_MS
894 : )
895 : }
896 :
897 0 : function retryHeldWrite(graph: LGraph, entry: HeldPromotedWrite): void {
898 0 : if (canvasReplaced(graph, entry.event)) return
899 0 : if ((deps.boundRootGraphId() ?? graph.id) !== entry.rootGraphId) {
900 0 : refuseWidgetWrite(entry.rootGraphId, entry.event, {
901 : reason: 'workflow_changed'
902 : })
903 0 : return
904 : }
905 0 : routeSetWidget(entry.event, entry)
906 : }
907 :
908 0 : function reportRefusal(
909 : rootGraphId: string,
910 : event: IntentOf<'set_widget'>,
911 : refusal: PromotedWriteRefusal
912 : ): void {
913 0 : const host = String(event.nodeId)
914 0 : switch (refusal.reason) {
915 : case 'layout_drift': {
916 0 : const { liveNames, doc } = refusal
917 0 : reportOnce(
918 : `promoted_drift:${rootGraphId}:${host}`,
919 : `Subgraph host ${host} promotes [${liveNames.join(', ')}], which the document's ${doc.valueCount} stored values and declared inputs [${doc.declaredNames.join(', ')}] do not place; refusing to mint a promoted write`,
920 : 'agent_crdt_promoted_widget_order_drift',
921 : {
922 : nodeId: event.nodeId,
923 : liveNames,
924 : docValueCount: doc.valueCount,
925 : docDeclaredNames: doc.declaredNames,
926 : docPromotedNames: doc.promotedNames
927 : },
928 : reportedRefusals
929 : )
930 0 : return
931 : }
932 : case 'unpromoted_widget':
933 0 : reportOnce(
934 : `promoted_unpromoted:${rootGraphId}:${host}:${event.name}`,
935 : `Widget ${event.name} on subgraph host ${host} is not one of its promoted inputs [${refusal.liveNames.join(', ')}]; refusing to mint`,
936 : 'agent_crdt_promoted_widget_not_promoted',
937 : {
938 : nodeId: event.nodeId,
939 : widget: event.name,
940 : liveNames: refusal.liveNames
941 : },
942 : reportedRefusals
943 : )
944 0 : return
945 : case 'workflow_changed':
946 0 : reportOnce(
947 : `promoted_workflow_changed:${rootGraphId}:${host}`,
948 : `Subgraph host ${host} was edited while the bound document caught up, and the bound workflow changed before it did; refusing to mint a promoted write`,
949 : 'agent_crdt_promoted_widget_workflow_changed',
950 : { nodeId: event.nodeId, widget: event.name },
951 : reportedRefusals
952 : )
953 0 : return
954 : case 'doc_not_synced':
955 0 : reportOnce(
956 : `promoted_unsynced:${rootGraphId}:${host}`,
957 : `Subgraph host ${host} was edited before the bound document caught up; refusing to mint a promoted write`,
958 : 'agent_crdt_promoted_widget_doc_not_synced',
959 : { nodeId: event.nodeId, widget: event.name },
960 : reportedRefusals
961 : )
962 0 : return
963 : default: {
964 : const unhandled: never = refusal
965 0 : return unhandled
966 : }
967 : }
968 : }
969 :
970 0 : function mintSetNodeField(event: IntentOf<'set_node_field'>): void {
971 0 : if (pendingAdds.has(nodeKey(event.graph.id, event.nodeId))) return
972 0 : if (!isMintableRootScope(event.graph, 'set_node_field', event.nodeId))
973 0 : return
974 0 : const {
975 : type: _type,
976 : graph: _graph,
977 : nodeId,
978 : source: _source,
979 : ...write
980 : } = event
981 0 : schedule({
982 : kind: 'op',
983 : operation: { op: 'set_node_field', node_id: nodeId, ...write }
984 : })
985 : }
986 :
987 0 : function mintRemoveNode(event: IntentOf<'remove_node'>): void {
988 0 : if (!isMintableRootScope(event.graph, 'node_delete', event.node.id)) return
989 0 : for (const [key, state] of pendingDynamicSlots)
990 0 : if (state.nodeId === event.node.id) pendingDynamicSlots.delete(key)
991 0 : for (const [key, pending] of pendingWidgetValues)
992 0 : if (pending.nodeId === event.node.id) pendingWidgetValues.delete(key)
993 0 : const key = nodeKey(event.graph.id, event.node.id)
994 0 : if (pendingAdds.get(key) === event.node) {
995 0 : pendingAdds.delete(key)
996 0 : pending = withoutCancelledAdd(pending, event.node.id)
997 0 : return
998 : }
999 0 : schedule({
1000 : kind: 'op',
1001 : operation: {
1002 : op: 'delete_node',
1003 : node_id: event.node.id,
1004 : removed_links: [...event.removedLinkIds]
1005 : }
1006 : })
1007 : }
1008 :
1009 0 : function reportSlotNotInDoc(
1010 : action: 'connect' | 'disconnect',
1011 : link: LLink,
1012 : input: INodeInputSlot
1013 : ): void {
1014 0 : reportOnce(
1015 : `${action}:${link.target_id}:${input.name}`,
1016 : `${action} targets input ${input.name} of node ${String(link.target_id)}, which the bound document does not carry; the bound doc diverges from the local graph`,
1017 : 'agent_crdt_link_slot_not_in_doc',
1018 : { action, linkId: link.id, nodeId: link.target_id, input: input.name }
1019 : )
1020 : }
1021 :
1022 0 : function mintMissingSlotConnect(
1023 : rootGraphId: string,
1024 : link: LLink,
1025 : target: LGraphNode | null | undefined,
1026 : input: INodeInputSlot | undefined,
1027 : slotKey: string | undefined,
1028 : pendingSlot: PendingDynamicSlot | undefined,
1029 : connect: DeferredDynamicConnect['operation']
1030 : ): void {
1031 0 : const growth = growForMissingSlot(target, input)
1032 0 : if (growth?.selection) {
1033 0 : if (!documentMatchesSelection(link.target_id, growth.selection)) {
1034 0 : if (input) reportSlotNotInDoc('connect', link, input)
1035 0 : return
1036 : }
1037 0 : if (pendingSlot) {
1038 0 : pendingSlot.deferred.push({ kind: 'connect', operation: connect })
1039 0 : retryDynamicSlotsSoon()
1040 0 : return
1041 : }
1042 : }
1043 0 : if (!growth) {
1044 0 : if (input) reportSlotNotInDoc('connect', link, input)
1045 0 : return
1046 : }
1047 0 : scheduleGrowthConnect(rootGraphId, link, input, slotKey, connect, growth)
1048 : }
1049 :
1050 0 : function scheduleGrowthConnect(
1051 : rootGraphId: string,
1052 : link: LLink,
1053 : input: INodeInputSlot | undefined,
1054 : slotKey: string | undefined,
1055 : connect: DeferredDynamicConnect['operation'],
1056 : growth: MissingSlotGrowth
1057 : ): void {
1058 0 : schedule({
1059 : kind: 'op',
1060 : operation: { ...connect, to_slot: null, grow: growth.grow }
1061 : })
1062 0 : if (!growth.selection || !input || !slotKey) return
1063 0 : pendingDynamicSlots.set(slotKey, {
1064 : rootGraphId,
1065 : nodeId: link.target_id,
1066 : inputName: input.name,
1067 : growLinkId: link.id,
1068 : since: performance.now(),
1069 : sent: false,
1070 : deferred: []
1071 : })
1072 0 : retryDynamicSlotsSoon()
1073 : }
1074 :
1075 0 : function mintConnect(event: IntentOf<'connect'>): void {
1076 0 : if (!isMintableRootScope(event.graph, 'connect', event.link.id)) return
1077 0 : const { link } = event
1078 0 : const target = event.graph.getNodeById(link.target_id)
1079 0 : const input = target?.inputs[link.target_slot]
1080 : const docNames = deps.docInputNames(link.target_id)
1081 0 : const toSlot = docInputIndex(docNames, input, link.target_slot)
1082 0 : const rootGraphId = event.graph.rootGraph.id
1083 0 : const slotKey = input
1084 : ? dynamicSlotKey(rootGraphId, link.target_id, input.name)
1085 : : undefined
1086 0 : const pendingSlot = slotKey ? pendingDynamicSlots.get(slotKey) : undefined
1087 0 : if (pendingSlot && toSlot !== undefined) releaseDynamicSlot(pendingSlot)
1088 0 : const connect = {
1089 : op: 'connect',
1090 : link_id: link.id,
1091 : from_node: link.origin_id,
1092 : from_slot: link.origin_slot,
1093 : to_node: link.target_id,
1094 : link_type: String(link.type)
1095 : } as const
1096 0 : if (toSlot !== undefined) {
1097 0 : schedule({ kind: 'op', operation: { ...connect, to_slot: toSlot } })
1098 0 : return
1099 : }
1100 0 : mintMissingSlotConnect(
1101 : rootGraphId,
1102 : link,
1103 : target,
1104 : input,
1105 : slotKey,
1106 : pendingSlot,
1107 : connect
1108 : )
1109 : }
1110 :
1111 0 : function mintMissingSlotDisconnect(
1112 : link: LLink,
1113 : input: INodeInputSlot | undefined,
1114 : slotKey: string | undefined,
1115 : pendingSlot: PendingDynamicSlot | undefined
1116 : ): void {
1117 0 : if (!pendingSlot) {
1118 0 : if (input) reportSlotNotInDoc('disconnect', link, input)
1119 0 : return
1120 : }
1121 0 : if (!pendingSlot.sent && pendingSlot.growLinkId === link.id) {
1122 0 : pending = pending.filter(
1123 : (entry) =>
1124 : entry.kind !== 'op' ||
1125 : entry.operation.op !== 'connect' ||
1126 : entry.operation.link_id !== link.id ||
1127 : !('grow' in entry.operation)
1128 : )
1129 0 : if (slotKey) pendingDynamicSlots.delete(slotKey)
1130 0 : return
1131 : }
1132 0 : pendingSlot.deferred.push({
1133 : kind: 'disconnect',
1134 : operation: {
1135 : op: 'disconnect',
1136 : link_id: link.id,
1137 : to_node: link.target_id
1138 : }
1139 : })
1140 0 : retryDynamicSlotsSoon()
1141 : }
1142 :
1143 0 : function mintDisconnect(event: IntentOf<'disconnect'>): void {
1144 0 : if (!isMintableRootScope(event.graph, 'disconnect', event.link.id)) return
1145 0 : const { link } = event
1146 0 : const input = event.graph.getNodeById(link.target_id)?.inputs[
1147 : link.target_slot
1148 : ]
1149 0 : const slotKey = input
1150 : ? dynamicSlotKey(event.graph.rootGraph.id, link.target_id, input.name)
1151 : : undefined
1152 0 : const pendingSlot = slotKey ? pendingDynamicSlots.get(slotKey) : undefined
1153 0 : const toSlot = docInputIndex(
1154 : deps.docInputNames(link.target_id),
1155 : input,
1156 : link.target_slot
1157 : )
1158 0 : if (toSlot === undefined) {
1159 0 : mintMissingSlotDisconnect(link, input, slotKey, pendingSlot)
1160 0 : return
1161 : }
1162 0 : if (pendingSlot) releaseDynamicSlot(pendingSlot)
1163 0 : schedule({
1164 : kind: 'op',
1165 : operation: {
1166 : op: 'disconnect',
1167 : link_id: link.id,
1168 : to_node: link.target_id,
1169 : to_slot: toSlot
1170 : }
1171 : })
1172 : }
1173 :
1174 0 : function mintClear(event: IntentOf<'clear'>): void {
1175 0 : if (event.nodeIds.length === 0) return
1176 0 : const boundRootGraphId = deps.boundRootGraphId()
1177 0 : if (boundRootGraphId !== null && event.graphId !== boundRootGraphId) {
1178 0 : reportOnce(
1179 : `clear:${event.graphId}:${boundRootGraphId}`,
1180 : `clear targets graph ${event.graphId}, not the bound document's root graph ${boundRootGraphId}; refusing to mint`,
1181 : 'agent_crdt_op_for_unbound_graph',
1182 : { graphId: event.graphId, boundRootGraphId }
1183 : )
1184 0 : return
1185 : }
1186 0 : schedule({
1187 : kind: 'op',
1188 : operation: { op: 'clear', removed_nodes: [...event.nodeIds] }
1189 : })
1190 : }
1191 :
1192 0 : function mintAddNode(event: IntentOf<'add_node'>): void {
1193 0 : if (!isMintableRootScope(event.graph, 'node_create', event.node.id)) return
1194 0 : pendingAdds.set(nodeKey(event.graph.id, event.node.id), event.node)
1195 0 : schedule({ kind: 'add_node', graph: event.graph, node: event.node })
1196 : }
1197 :
1198 0 : function discardHeldWrite(event: GraphIntentEvent): void {
1199 0 : if (event.type === 'set_widget')
1200 0 : heldPromotedWrites.delete(heldWriteKey(event))
1201 : }
1202 :
1203 0 : function intentRootGraphId(
1204 : event: GraphIntentEvent,
1205 : graph: LGraph | null
1206 : ): string | null {
1207 0 : if ('graph' in event) return event.graph.rootGraph.id
1208 0 : return graph !== null && reachableIntentGraph(graph, event.graphId) !== null
1209 : ? graph.id
1210 : : null
1211 : }
1212 :
1213 0 : function noteUnboundLocalIntent(event: GraphIntentEvent): void {
1214 0 : const graph = deps.getGraph()
1215 0 : const eventRootGraphId = intentRootGraphId(event, graph)
1216 0 : if (eventRootGraphId === null) return
1217 0 : if (eventRootGraphId === deps.boundRootGraphId())
1218 0 : deps.onUnboundLocalIntent?.()
1219 0 : else if (eventRootGraphId === graph?.id) deps.onUnboundVisibleIntent?.()
1220 : }
1221 :
1222 4 : function onIntent(event: GraphIntentEvent): void {
1223 4 : if (event.source !== 'local') return
1224 4 : if (deps.isEnabled() && deps.isDocBound()) {
1225 0 : mintIntent(event)
1226 0 : return
1227 : }
1228 0 : if (deps.isEnabled()) noteUnboundLocalIntent(event)
1229 0 : discardHeldWrite(event)
1230 : }
1231 :
1232 0 : function mintIntent(event: GraphIntentEvent): void {
1233 0 : switch (event.type) {
1234 : case 'add_node':
1235 0 : mintAddNode(event)
1236 0 : return
1237 : case 'remove_node':
1238 0 : mintRemoveNode(event)
1239 0 : return
1240 : case 'connect':
1241 0 : mintConnect(event)
1242 0 : return
1243 : case 'disconnect':
1244 0 : mintDisconnect(event)
1245 0 : return
1246 : case 'clear':
1247 0 : mintClear(event)
1248 0 : return
1249 : case 'set_widget':
1250 0 : routeSetWidget(event, null)
1251 0 : return
1252 : case 'set_node_field':
1253 0 : mintSetNodeField(event)
1254 0 : return
1255 : }
1256 : }
1257 :
1258 1 : const detachIntents = onGraphIntent(onIntent)
1259 :
1260 : // The same gate also answers litegraph's mint-time question: a graph whose
1261 : // edits reach the doc is a graph the agent mints into too, and must mint
1262 : // node ids from the disjoint range (`idAllocation.ts`).
1263 1 : const unregisterDocBoundProbe = registerDocBoundRootGraphProbe(() => {
1264 0 : if (!deps.isEnabled() || !deps.isDocBound()) return null
1265 0 : const graph = deps.getGraph()
1266 0 : if (!graph) return null
1267 0 : return graph.rootGraph.id
1268 : })
1269 :
1270 1 : return {
1271 : detach() {
1272 0 : detached = true
1273 0 : pending = []
1274 0 : pendingAdds.clear()
1275 0 : pendingDynamicSlots.clear()
1276 0 : pendingWidgetValues.clear()
1277 0 : heldPromotedWrites.clear()
1278 0 : if (heldRetryTimer !== null) clearTimeout(heldRetryTimer)
1279 0 : heldRetryTimer = null
1280 0 : if (dynamicSlotRetryTimer !== null) clearTimeout(dynamicSlotRetryTimer)
1281 0 : dynamicSlotRetryTimer = null
1282 0 : detachIntents()
1283 0 : unregisterDocBoundProbe()
1284 : }
1285 : }
1286 : }
|