LCOV - code coverage report
Current view: top level - src/workbench/extensions/agent/crdt - liveGraphApplier.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 2.4 % 906 22
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import {
       2              :   linksMap,
       3              :   nodesMap,
       4              :   OPAQUE_WIDGETS_KEY,
       5              :   readStamps,
       6              :   WIDGET_FORM_KEY
       7              : } from '@comfyorg/comfy-multi-player'
       8              : import { isEqual, isPlainObject, omit } from 'es-toolkit'
       9              : import * as Y from 'yjs'
      10              : import { z } from 'zod'
      11              : 
      12              : import {
      13              :   applyRemoteDynamicGroupRowCount,
      14              :   dynamicGroupRowAllocationBound,
      15              :   isDynamicGroupController,
      16              :   reachesDynamicGroupRowCount,
      17              :   reportRemoteDynamicGroupRowMismatch
      18              : } from '@/core/graph/widgets/dynamicGroupDiagnostics'
      19              : import { growAutogrowInput } from '@/core/graph/widgets/dynamicWidgets'
      20              : import type { INodeFlags } from '@comfyorg/graph-model/interfaces'
      21              : import type { INodeInputSlot } from '@comfyorg/graph-model/slots'
      22              : import { LGraphCanvas } from '@/lib/litegraph/src/LGraphCanvas'
      23              : import { withGraphIntentSource } from '@/lib/litegraph/src/graphIntents'
      24              : import { detachSerialisedLinks } from '@/lib/litegraph/src/linkDeduplication'
      25              : import {
      26              :   LGraphGroup,
      27              :   LGraphNode,
      28              :   LiteGraph
      29              : } from '@/lib/litegraph/src/litegraph'
      30              : import type { LGraph } from '@/lib/litegraph/src/litegraph'
      31              : import { containsCentre } from '@/lib/litegraph/src/measure'
      32              : import { topologicalSortSubgraphs } from '@/lib/litegraph/src/subgraph/subgraphDeduplication'
      33              : import type {
      34              :   ExportedSubgraph,
      35              :   ISerialisableNodeInput,
      36              :   ISerialisableNodeOutput,
      37              :   ISerialisedGroup,
      38              :   ISerialisedNode
      39              : } from '@comfyorg/graph-model/serialisation'
      40              : import type { IBaseWidget } from '@comfyorg/graph-model/widgets'
      41              : import { isWidgetValue } from '@comfyorg/graph-model/widgets'
      42              : import type { ComfyInputsSpec } from '@comfyorg/object-info-parser'
      43              : import {
      44              :   zDynamicComboOption,
      45              :   zDynamicComboSpecV2
      46              : } from '@comfyorg/object-info-parser'
      47              : import { transformInputSpecV1ToV2 } from '@comfyorg/object-info-parser/migration'
      48              : import type { InputSpec as InputSpecV2 } from '@comfyorg/object-info-parser/schemas/nodeDefSchemaV2'
      49              : import { reportError } from '@comfyorg/telemetry/reportError'
      50              : import { zComfyNode, zGroup } from '@comfyorg/graph-model/workflowSchema'
      51              : import { BaseWidget } from '@/lib/litegraph/src/widgets/BaseWidget'
      52              : import { inputSpecTree } from '@/core/graph/nodeDef/inputSpecInterpreter'
      53              : import { isUuidShapedSubgraphId } from '@/schemas/subgraphIdSchema'
      54              : import type { LinkId } from '@comfyorg/graph-model/linkId'
      55              : import { parseLinkId, toLinkId } from '@comfyorg/graph-model/linkId'
      56              : import type { NodeId } from '@comfyorg/graph-model/nodeId'
      57              : import { toNodeId } from '@comfyorg/graph-model/nodeId'
      58              : import type { WidgetValue } from '@/types/simplifiedWidget'
      59              : 
      60              : import { withLiveAgentTurnWrites } from './agentRemoteProvenance'
      61              : import {
      62              :   allSubgraphDefinitions,
      63              :   readSubgraphDefinitions,
      64              :   readSubgraphInteriorWidgets
      65              : } from './agentSubgraphDefinitions'
      66              : import type {
      67              :   Bounds as PlacementRect,
      68              :   ReadOnlyRect,
      69              :   Rect
      70              : } from '@comfyorg/shared-frontend-utils/geometry'
      71              : import { placementOffset } from './batchPlacement'
      72              : 
      73              : export type NodeChange = 'add' | 'update' | 'delete'
      74              : 
      75              : /**
      76              :  * What one delivered document frame touched, as collected from Y observers.
      77              :  * Ids are document keys (strings); the applier resolves them against the live
      78              :  * graph.
      79              :  */
      80              : 
      81              : type InteriorChanges = ReadonlyMap<
      82              :   string,
      83              :   ReadonlyMap<string, ReadonlySet<string> | 'all'>
      84              : >
      85              : 
      86              : export interface FrameChanges {
      87              :   nodes: ReadonlyMap<string, NodeChange>
      88              :   /** Widget names edited per node, or `'all'` when the storage was replaced. */
      89              :   widgets: ReadonlyMap<string, ReadonlySet<string> | 'all'>
      90              :   /** Synced node-map keys edited per node. */
      91              :   resyncNodes: ReadonlyMap<string, ReadonlySet<string>>
      92              :   links: ReadonlySet<string>
      93              : 
      94              :   interiors?: InteriorChanges
      95              : 
      96              :   interiorDefinitions?: ReadonlySet<string>
      97              : 
      98              :   /** Root group ids that `meta.groups` gained or lost. */
      99              :   groups?: ReadonlySet<string>
     100              : }
     101              : 
     102              : export interface RemoteApplyContext {
     103              :   actor: string
     104              :   opIds: readonly string[]
     105              :   liveAgentTurn?: boolean
     106              : }
     107              : 
     108              : export interface LiveGraphApplierDeps {
     109              :   getGraph(): LGraph | null
     110              :   getCanvas?(): LGraphCanvas | null | undefined
     111              :   /** Scopes layout provenance to the remote actor while `fn` writes. */
     112              :   withRemoteActor?<T>(actor: string, fn: () => T): T
     113              :   viewportBounds?(): PlacementRect | null
     114              :   /**
     115              :    * True when a local write to the widget register is still in flight and
     116              :    * `docValue` is not it; the frame's value is then left unapplied so the
     117              :    * register is not rewound under the edit.
     118              :    */
     119              :   holdsLocalWrite?(nodeId: string, widget: string, docValue: unknown): boolean
     120              : }
     121              : 
     122              : export interface ApplyResult {
     123              :   createdNodeIds: NodeId[]
     124              :   failureCount: number
     125              : }
     126              : 
     127              : /**
     128              :  * `merge` applies one frame's changes on top of the live graph. `replace`
     129              :  * applies the first frame of a new document lineage: the document is the
     130              :  * whole graph, so live nodes and links it does not hold are removed.
     131              :  */
     132              : export type ApplyMode = 'merge' | 'replace'
     133              : 
     134              : /**
     135              :  * Node-map keys mirrored onto a live node when the document edits them.
     136              :  * Structural keys (`inputs`, `outputs`, `pos`, `size`, widget storage) are
     137              :  * excluded: slots follow links, layout stays local.
     138              :  */
     139            1 : export const SYNCED_NODE_FIELDS: ReadonlySet<string> = new Set([
     140              :   'title',
     141              :   'mode',
     142              :   'flags',
     143              :   'properties',
     144              :   'color',
     145              :   'bgcolor',
     146              :   'boxcolor',
     147              :   'shape',
     148              :   'showAdvanced'
     149              : ])
     150              : 
     151            1 : const SYNCED_APPEARANCE_FIELDS = [
     152              :   'color',
     153              :   'bgcolor',
     154              :   'boxcolor',
     155              :   'shape',
     156              :   'showAdvanced'
     157              : ] as const
     158              : 
     159            1 : const AGENT_APPLY_TAGS = { subsystem: 'agent-crdt', layer: 'graph-api' }
     160              : 
     161              : type DocNode = {
     162              :   id: string
     163              :   type: string
     164              :   serialised: ISerialisedNode
     165              : } & (
     166              :   | {
     167              :       widgets: Record<string, unknown> | unknown[] | undefined
     168              :       widgetRecord?: never
     169              :     }
     170              :   | { widgets?: never; widgetRecord: Record<string, unknown> }
     171              : )
     172              : 
     173              : interface DocLink {
     174              :   id: LinkId
     175              :   origin: string
     176              :   originSlot: number
     177              :   target: string
     178              :   targetSlot: number
     179              : }
     180              : 
     181              : interface ApplyWidgetOptions {
     182              :   documentWidgets?: DocNode['widgets']
     183              :   reportMissing?: boolean
     184              : }
     185              : 
     186            0 : function plain(value: unknown): unknown {
     187            0 :   if (value instanceof Y.Map || value instanceof Y.Array) return value.toJSON()
     188            0 :   return structuredClone(value)
     189              : }
     190              : 
     191              : /**
     192              :  * `flags.ghost` marks a node the user is still placing; the snapshot minted
     193              :  * while placement is live carries it, but the flag is local interaction
     194              :  * state, never document state.
     195              :  */
     196            0 : function syncedFlags(flags: INodeFlags | undefined): INodeFlags {
     197            0 :   const { ghost: _ghost, ...rest } = flags ?? {}
     198            0 :   return rest
     199              : }
     200              : 
     201            1 : const zDocSlot = z
     202              :   .object({
     203              :     name: z.string(),
     204              :     type: z.union([z.string(), z.array(z.string()).nonempty(), z.number()])
     205              :   })
     206              :   .passthrough()
     207            1 : const zWidgetRecord = z
     208              :   .record(z.string(), z.unknown())
     209              :   .refine((record) => !Object.hasOwn(record, 'length'), 'has a length key')
     210            1 : const zNodeProperty = z.union([
     211              :   z.string(),
     212              :   z.number(),
     213              :   z.boolean(),
     214              :   z.object({}).passthrough(),
     215              :   z.array(z.unknown()),
     216              :   z.null()
     217              : ])
     218              : 
     219              : /**
     220              :  * The shape a document node must have before it can configure a live node.
     221              :  * Agent-minted nodes are sparse, so geometry and mode fall back to defaults;
     222              :  * slot and property shapes are enforced because `LGraphNode.configure` maps
     223              :  * over them without checking. Slot link references are not validated because
     224              :  * `detachSerialisedLinks` discards them; links come from the links map.
     225              :  * Widget values live in the node's `widgets` map, never in `widgets_values`.
     226              :  */
     227            1 : const zDocNodeFields = zComfyNode
     228              :   .partial({ pos: true, size: true, flags: true, order: true, mode: true })
     229              :   .omit({ widgets_values: true })
     230              :   .extend({
     231              :     id: z.string(),
     232              :     type: z.string().min(1),
     233              :     title: z.string().optional(),
     234              :     inputs: z.array(zDocSlot).optional(),
     235              :     outputs: z.array(zDocSlot).optional(),
     236              :     properties: z.record(z.string(), zNodeProperty.optional()).optional(),
     237              :     [OPAQUE_WIDGETS_KEY]: zWidgetRecord.optional()
     238              :   })
     239              : 
     240            1 : const zDocGroup = zGroup.extend({ id: z.unknown().optional() })
     241              : 
     242              : /**
     243              :  * The `meta.groups` records that configure a canvas group, keyed by id; a
     244              :  * record without a usable id is keyed by a hash of its content.
     245              :  */
     246            0 : export function readDocGroups(groups: unknown): Map<string, ISerialisedGroup> {
     247            0 :   const parsed = new Map<string, ISerialisedGroup>()
     248            0 :   if (!Array.isArray(groups)) return parsed
     249            0 :   for (const record of groups) {
     250            0 :     const group = zDocGroup.safeParse(structuredClone(record))
     251            0 :     if (!group.success) continue
     252            0 :     const id = isGroupId(group.data.id)
     253              :       ? group.data.id
     254              :       : contentGroupId(group.data)
     255            0 :     parsed.set(String(id), { ...group.data, id })
     256              :   }
     257            0 :   return parsed
     258              : }
     259              : 
     260            0 : function isGroupId(id: unknown): id is number {
     261            0 :   return typeof id === 'number' && Number.isSafeInteger(id) && id > 0
     262              : }
     263              : 
     264            0 : function contentGroupId(record: Record<string, unknown>): number {
     265            0 :   const json = canonicalJson(record)
     266            0 :   let h1 = 0xdeadbeef
     267            0 :   let h2 = 0x41c6ce57
     268            0 :   for (let i = 0; i < json.length; i++) {
     269            0 :     const code = json.charCodeAt(i)
     270            0 :     h1 = Math.imul(h1 ^ code, 2654435761)
     271            0 :     h2 = Math.imul(h2 ^ code, 1597334677)
     272              :   }
     273            0 :   h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507)
     274            0 :   h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909)
     275            0 :   h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507)
     276            0 :   h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909)
     277            0 :   return 4294967296 * (2097151 & h2) + (h1 >>> 0) + 1
     278              : }
     279              : 
     280            0 : function canonicalJson(value: unknown): string {
     281            0 :   if (typeof value === 'bigint') return `${value}n`
     282            0 :   if (value === undefined) return 'null'
     283            0 :   if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`
     284            0 :   if (value !== null && typeof value === 'object') {
     285              :     const entries = Object.entries(value)
     286              :       .filter(([, item]) => item !== undefined)
     287              :       .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
     288              :       .map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`)
     289            0 :     return `{${entries.join(',')}}`
     290              :   }
     291            0 :   return JSON.stringify(value)
     292              : }
     293              : 
     294              : /**
     295              :  * Only the actor's kind is reported: the segments after it in
     296              :  * `agent:<thread>:<turn>` and `human:<user>:<tab>` identify a user.
     297              :  */
     298              : type ActorKind = 'agent' | 'human' | 'unknown'
     299              : type NodeProducer =
     300              :   | { origin: 'operation'; actorKind: ActorKind; opId: string; version: number }
     301              :   | { origin: 'unstamped' | 'unreadable' }
     302              : 
     303              : interface MalformedDocNode {
     304              :   malformed: string
     305              :   discriminate(): {
     306              :     classType?: string
     307              :     valueShapes: string
     308              :     producer: NodeProducer
     309              :   }
     310              : }
     311              : 
     312            1 : const MAX_SHAPED_ELEMENTS = 16
     313            1 : const MAX_DIAGNOSTIC_CHARS = 1024
     314            1 : const MAX_REPORTED_OP_IDS = 4
     315            1 : const OMISSION_MARKER_CHARS = 8
     316            1 : const MAX_DIAGNOSTIC_LIST_CHARS = 320
     317              : 
     318              : interface DiagnosticString {
     319              :   path: readonly (string | number)[]
     320              :   value: string
     321              : }
     322              : 
     323            0 : function elementShape(value: unknown): string {
     324            0 :   if (value === null) return 'null'
     325            0 :   if (Array.isArray(value)) return 'array'
     326            0 :   return typeof value
     327              : }
     328              : 
     329            0 : function valueShape(value: unknown): string {
     330            0 :   if (value === null) return 'null'
     331            0 :   if (Array.isArray(value)) {
     332            0 :     const shaped = value.slice(0, MAX_SHAPED_ELEMENTS).map(elementShape)
     333            0 :     const omitted = value.length - shaped.length
     334            0 :     if (omitted > 0) shaped.push(`+${omitted}`)
     335            0 :     return `array:${value.length}[${shaped.join(',')}]`
     336              :   }
     337            0 :   if (typeof value === 'object') return `object:${Object.keys(value).length}`
     338            0 :   return typeof value
     339              : }
     340              : 
     341            0 : function diagnosticWidgetNames(widgets: readonly IBaseWidget[]): string[] {
     342            0 :   const names: string[] = []
     343            0 :   let usedChars = 0
     344            0 :   for (const widget of widgets.slice(0, MAX_SHAPED_ELEMENTS)) {
     345            0 :     if (usedChars + widget.name.length > MAX_DIAGNOSTIC_LIST_CHARS) break
     346            0 :     names.push(widget.name)
     347            0 :     usedChars += widget.name.length
     348              :   }
     349            0 :   const omitted = widgets.length - names.length
     350            0 :   if (omitted > 0) names.push(`+${omitted}`)
     351            0 :   return names
     352              : }
     353              : 
     354            0 : function diagnosticStrings(
     355              :   value: unknown,
     356              :   path: readonly (string | number)[] = []
     357              : ): DiagnosticString[] {
     358            0 :   if (typeof value === 'string') return [{ path, value }]
     359            0 :   if (Array.isArray(value)) {
     360            0 :     return value.flatMap((entry, index) =>
     361              :       diagnosticStrings(entry, [...path, index])
     362              :     )
     363              :   }
     364            0 :   if (!isPlainObject(value)) return []
     365            0 :   return Object.entries(value).flatMap(([key, entry]) =>
     366              :     diagnosticStrings(entry, [...path, key])
     367              :   )
     368              : }
     369              : 
     370            0 : function diagnosticPath(path: readonly (string | number)[]): string {
     371            0 :   return JSON.stringify(path)
     372              : }
     373              : 
     374            0 : function replaceDiagnosticValue(
     375              :   value: unknown,
     376              :   path: readonly (string | number)[],
     377              :   replacements: ReadonlyMap<string, string>
     378              : ): unknown {
     379            0 :   if (typeof value === 'string') {
     380            0 :     return replacements.get(diagnosticPath(path)) ?? value
     381              :   }
     382            0 :   if (Array.isArray(value)) {
     383            0 :     return value.map((entry, index) =>
     384              :       replaceDiagnosticValue(entry, [...path, index], replacements)
     385              :     )
     386              :   }
     387            0 :   if (!isPlainObject(value)) return value
     388            0 :   return Object.fromEntries(
     389              :     Object.entries(value).map(([key, entry]) => [
     390              :       key,
     391              :       replaceDiagnosticValue(entry, [...path, key], replacements)
     392              :     ])
     393              :   )
     394              : }
     395              : 
     396            0 : function replaceDiagnosticStrings(
     397              :   context: Record<string, unknown>,
     398              :   replacements: ReadonlyMap<string, string>
     399              : ): Record<string, unknown> {
     400            0 :   return Object.fromEntries(
     401              :     Object.entries(context).map(([key, value]) => [
     402              :       key,
     403              :       replaceDiagnosticValue(value, [key], replacements)
     404              :     ])
     405              :   )
     406              : }
     407              : 
     408            0 : function boundedContext(
     409              :   context: Record<string, unknown>
     410              : ): Record<string, unknown> {
     411            0 :   const shortestFirst = diagnosticStrings(context).sort(
     412              :     (left, right) => left.value.length - right.value.length
     413              :   )
     414            0 :   let remaining = MAX_DIAGNOSTIC_CHARS
     415            0 :   const truncated = new Map<string, string>()
     416            0 :   for (const { path, value } of shortestFirst) {
     417            0 :     if (value.length <= remaining) {
     418            0 :       remaining -= value.length
     419            0 :       continue
     420              :     }
     421            0 :     const kept = value.slice(0, Math.max(0, remaining - OMISSION_MARKER_CHARS))
     422            0 :     truncated.set(
     423              :       diagnosticPath(path),
     424              :       kept === '' ? '' : `${kept}+${value.length - kept.length}`
     425              :     )
     426            0 :     remaining = 0
     427              :   }
     428            0 :   if (truncated.size === 0) return context
     429            0 :   return replaceDiagnosticStrings(context, truncated)
     430              : }
     431              : 
     432              : /** `absent` when the path's own key is missing, so it is not read as `undefined`. */
     433            0 : function shapeAtPath(root: unknown, path: readonly PropertyKey[]): string {
     434            0 :   let cursor: unknown = root
     435            0 :   for (const [depth, key] of path.entries()) {
     436            0 :     if (cursor === null || typeof cursor !== 'object') return 'unreachable'
     437            0 :     if (!Object.hasOwn(cursor, key))
     438            0 :       return depth === path.length - 1 ? 'absent' : 'unreachable'
     439            0 :     cursor = Reflect.get(cursor, key)
     440              :   }
     441            0 :   return valueShape(cursor)
     442              : }
     443              : 
     444            0 : function issueShapes(fields: unknown, error: z.ZodError): string {
     445            0 :   return error.issues
     446              :     .map(
     447              :       (issue) =>
     448              :         `${issue.path.join('.')} ${issue.code} ${shapeAtPath(fields, issue.path)}`
     449              :     )
     450              :     .join('; ')
     451              : }
     452              : 
     453            0 : function actorKind(actor: unknown): ActorKind {
     454            0 :   const kind = typeof actor === 'string' ? actor.split(':', 1)[0] : ''
     455            0 :   return kind === 'agent' || kind === 'human' ? kind : 'unknown'
     456              : }
     457              : 
     458            0 : function diagnosticActor(actor: string): string {
     459            0 :   const kind = actorKind(actor)
     460            0 :   return kind !== 'unknown' && actor.split(':').length === 3 ? kind : actor
     461              : }
     462              : 
     463            0 : function diagnosticApplyContext(context: RemoteApplyContext) {
     464            0 :   const opIds = context.opIds.slice(0, MAX_REPORTED_OP_IDS)
     465            0 :   return boundedContext({
     466              :     actor: diagnosticActor(context.actor),
     467              :     opIds,
     468              :     omittedOpIdCount: context.opIds.length - opIds.length
     469              :   })
     470              : }
     471              : 
     472            0 : function diagnosticNodeOwner(graph: LGraph, nodeId: NodeId) {
     473            0 :   const owner = [graph.rootGraph, ...graph.rootGraph.subgraphs.values()].find(
     474              :     (candidate) => candidate.getNodeById(nodeId) !== null
     475              :   )
     476            0 :   if (owner === undefined) return { existingOwnerKind: 'unknown' }
     477            0 :   return {
     478              :     existingOwnerKind: owner === graph.rootGraph ? 'root' : 'subgraph',
     479              :     existingOwnerGraphId: owner.id
     480              :   }
     481              : }
     482              : 
     483            0 : function nodeProducer(doc: Y.Doc, id: string): NodeProducer {
     484            0 :   let stamps: Readonly<Record<string, unknown>>
     485            0 :   try {
     486            0 :     stamps = readStamps(doc)
     487              :   } catch {
     488            0 :     return { origin: 'unreadable' }
     489              :   }
     490            0 :   const key = JSON.stringify(['node', id])
     491            0 :   if (!Object.hasOwn(stamps, key)) return { origin: 'unstamped' }
     492            0 :   const stamp = stamps[key]
     493            0 :   if (!Array.isArray(stamp)) return { origin: 'unreadable' }
     494            0 :   const [version, actor, opId]: unknown[] = stamp
     495            0 :   if (typeof version !== 'number' || typeof opId !== 'string')
     496            0 :     return { origin: 'unreadable' }
     497            0 :   return {
     498              :     origin: 'operation',
     499              :     actorKind: actorKind(actor),
     500              :     opId,
     501              :     version
     502              :   }
     503              : }
     504              : 
     505            0 : function readDocNode(
     506              :   doc: Y.Doc,
     507              :   id: string
     508              : ): DocNode | MalformedDocNode | null {
     509            0 :   const source = nodesMap(doc).get(id)
     510            0 :   if (!(source instanceof Y.Map)) return null
     511              : 
     512            0 :   const fields: Record<string, unknown> = { id }
     513            0 :   let widgets: DocNode['widgets']
     514            0 :   let record: unknown
     515            0 :   source.forEach((value, key) => {
     516            0 :     if (key === 'widgets' && value instanceof Y.Map) {
     517            0 :       widgets = value.toJSON()
     518            0 :     } else if (key === OPAQUE_WIDGETS_KEY) {
     519            0 :       const opaque = plain(value)
     520            0 :       if (Array.isArray(opaque)) widgets = opaque
     521            0 :       else if (isPlainObject(opaque)) record = opaque
     522            0 :     } else if (key !== 'id' && key !== WIDGET_FORM_KEY) {
     523            0 :       fields[key] = plain(value)
     524              :     }
     525              :   })
     526            0 :   if (widgets === undefined && record !== undefined)
     527            0 :     fields[OPAQUE_WIDGETS_KEY] = record
     528            0 :   const parsed = zDocNodeFields.safeParse(fields)
     529            0 :   if (!parsed.success) {
     530            0 :     const { error } = parsed
     531            0 :     return {
     532              :       malformed: error.issues
     533              :         .map((issue) => `${issue.path.join('.')} ${issue.message}`)
     534              :         .join('; '),
     535              :       discriminate() {
     536            0 :         return {
     537              :           classType: typeof fields.type === 'string' ? fields.type : undefined,
     538              :           valueShapes: issueShapes(fields, error),
     539              :           producer: nodeProducer(doc, id)
     540              :         }
     541              :       }
     542              :     }
     543              :   }
     544            0 :   const {
     545              :     pos = [0, 0],
     546              :     size = [0, 0],
     547              :     flags,
     548              :     order = 0,
     549              :     mode = 0,
     550              :     [OPAQUE_WIDGETS_KEY]: widgetRecord,
     551              :     ...rest
     552              :   } = parsed.data
     553            0 :   const serialised: ISerialisedNode = {
     554              :     ...rest,
     555              :     pos,
     556              :     size,
     557              :     flags: syncedFlags(flags),
     558              :     order,
     559              :     mode
     560              :   }
     561            0 :   const node = { id, type: serialised.type, serialised }
     562            0 :   return widgetRecord === undefined
     563              :     ? { ...node, widgets }
     564              :     : { ...node, widgetRecord }
     565              : }
     566              : 
     567            0 : function readDocLink(doc: Y.Doc, key: string): DocLink | null {
     568            0 :   const raw = linksMap(doc).get(key)
     569            0 :   const tuple = raw instanceof Y.Array ? raw.toArray() : raw
     570            0 :   const id = parseLinkId(key)
     571            0 :   if (id === undefined || id < 0 || !isLinkTuple(tuple, id)) return null
     572            0 :   return {
     573              :     id,
     574              :     origin: String(tuple[1]),
     575              :     originSlot: Number(tuple[2]),
     576              :     target: String(tuple[3]),
     577              :     targetSlot: Number(tuple[4])
     578              :   }
     579              : }
     580              : 
     581              : /** `[id, origin, originSlot, target, targetSlot, type]` with both endpoints present and integer slots. */
     582            0 : function isLinkTuple(tuple: unknown, id: LinkId): tuple is readonly unknown[] {
     583            0 :   if (!Array.isArray(tuple) || tuple.length < 5) return false
     584            0 :   const [tupleId, origin, originSlot, target, targetSlot] = tuple
     585            0 :   return (
     586              :     tupleId === id &&
     587              :     origin != null &&
     588              :     target != null &&
     589              :     Number.isInteger(Number(originSlot)) &&
     590              :     Number.isInteger(Number(targetSlot))
     591              :   )
     592              : }
     593              : 
     594              : /**
     595              :  * A document node's slot names in document order (an unnamed slot record is
     596              :  * `undefined` at its position), or null when the document has no such node
     597              :  * or no slot list for it.
     598              :  */
     599            0 : export function readDocSlotNames(
     600              :   doc: Y.Doc,
     601              :   nodeId: string,
     602              :   kind: 'inputs' | 'outputs'
     603              : ): readonly (string | undefined)[] | null {
     604            0 :   const slots = nodesMap(doc).get(nodeId)?.get(kind)
     605            0 :   const list: unknown = slots instanceof Y.Array ? slots.toJSON() : slots
     606            0 :   if (!Array.isArray(list)) return null
     607            0 :   return list.map((entry: unknown) => {
     608            0 :     const name =
     609              :       typeof entry === 'object' && entry !== null && 'name' in entry
     610              :         ? entry.name
     611              :         : undefined
     612            0 :     return typeof name === 'string' ? name : undefined
     613              :   })
     614              : }
     615              : 
     616            0 : function readDocSlotName(
     617              :   doc: Y.Doc,
     618              :   nodeId: string,
     619              :   kind: 'inputs' | 'outputs',
     620              :   slot: number
     621              : ): string | undefined {
     622            0 :   return readDocSlotNames(doc, nodeId, kind)?.[slot]
     623              : }
     624              : 
     625              : /** The document's value for a node's named widget, or undefined when it holds none. */
     626            0 : export function readDocWidgetValue(
     627              :   doc: Y.Doc,
     628              :   nodeId: string,
     629              :   widget: string
     630              : ): unknown {
     631            0 :   const widgets = nodesMap(doc).get(nodeId)?.get('widgets')
     632            0 :   return widgets instanceof Y.Map ? plain(widgets.get(widget)) : undefined
     633              : }
     634              : 
     635            0 : export function docLinksIncident(doc: Y.Doc, nodeId: string): DocLink[] {
     636            0 :   const links: DocLink[] = []
     637            0 :   linksMap(doc).forEach((_, key) => {
     638            0 :     const link = readDocLink(doc, key)
     639            0 :     if (link && (link.origin === nodeId || link.target === nodeId))
     640            0 :       links.push(link)
     641              :   })
     642            0 :   return links
     643              : }
     644              : 
     645              : /**
     646              :  * Runs `fn` so that the first link it mints receives `id`. The live graph's
     647              :  * link counter is monotonic; seeding it one below the document id lets
     648              :  * `connect` mint the document's id through its normal path, and the counter
     649              :  * is restored to the higher of the two afterwards so later local mints never
     650              :  * collide with ids the document has already handed out.
     651              :  */
     652            0 : function withLinkId<T>(graph: LGraph, id: LinkId, fn: () => T): T {
     653            0 :   if (graph.links.has(id)) return fn()
     654            0 :   const { state } = graph
     655            0 :   const previous = state.lastLinkId
     656            0 :   state.lastLinkId = toLinkId(id - 1)
     657            0 :   try {
     658            0 :     return fn()
     659              :   } finally {
     660            0 :     state.lastLinkId = toLinkId(Math.max(previous, state.lastLinkId))
     661              :   }
     662              : }
     663              : 
     664            0 : function serializableWidgets(node: LGraphNode): IBaseWidget[] {
     665            0 :   return (node.widgets ?? []).filter((widget) => widget.serialize !== false)
     666              : }
     667              : 
     668            0 : function supportsDynamicWidgetOverflow(node: LGraphNode): boolean {
     669            0 :   const inputs = node.constructor.nodeData?.inputs
     670            0 :   return (
     671              :     inputs !== undefined &&
     672              :     Object.values(inputs).some((spec) =>
     673              :       inputSpecTree(spec).some(({ type }) => type === 'COMFY_DYNAMICCOMBO_V3')
     674              :     )
     675              :   )
     676              : }
     677              : 
     678            1 : const MAX_OPTION_NESTING = 8
     679              : 
     680            1 : const VARIABLE_LENGTH_CONTROL_TYPES = new Set([
     681              :   'COMFY_AUTOGROW_V3',
     682              :   'COMFY_DYNAMICGROUP_V3'
     683              : ])
     684              : 
     685              : interface OptionGate {
     686              :   readonly selector: string
     687              :   readonly optionKey: string
     688              : }
     689              : 
     690              : interface OptionOwnedBranch {
     691              :   readonly prefix: string
     692              :   readonly gates: readonly OptionGate[]
     693              : }
     694              : 
     695              : interface OptionSelector {
     696              :   readonly name: string
     697              :   readonly widestOptionWidgetCount: number
     698              : }
     699              : 
     700              : interface OptionLayout {
     701              :   readonly branches: readonly OptionOwnedBranch[]
     702              :   readonly selectors: readonly OptionSelector[]
     703              : }
     704              : 
     705            1 : const NO_OPTION_LAYOUT: OptionLayout = { branches: [], selectors: [] }
     706              : 
     707            1 : const optionLayouts = new WeakMap<object, OptionLayout>()
     708              : 
     709            0 : function optionLayout(node: LGraphNode): OptionLayout {
     710            0 :   const { nodeData } = node.constructor
     711            0 :   if (!nodeData) return NO_OPTION_LAYOUT
     712            0 :   const cached = optionLayouts.get(nodeData)
     713            0 :   if (cached) return cached
     714              : 
     715            0 :   const branches: OptionOwnedBranch[] = []
     716            0 :   const selectors: OptionSelector[] = []
     717            0 :   for (const [name, spec] of Object.entries(nodeData.inputs)) {
     718            0 :     const combo = zDynamicComboSpecV2.safeParse(spec)
     719            0 :     if (!combo.success) continue
     720            0 :     selectors.push({
     721              :       name,
     722              :       widestOptionWidgetCount: widestOptionWidgetCount(combo.data, 0)
     723              :     })
     724            0 :     collectOptionOwnedBranches(name, combo.data, [], branches, 0)
     725              :   }
     726            0 :   const layout: OptionLayout = { branches, selectors }
     727            0 :   optionLayouts.set(nodeData, layout)
     728            0 :   return layout
     729              : }
     730              : 
     731            0 : function comboOptions(combo: {
     732              :   options: readonly unknown[]
     733              : }): { key: string; inputs: ComfyInputsSpec }[] {
     734            0 :   return combo.options.flatMap((candidate) => {
     735            0 :     const option = zDynamicComboOption.safeParse(candidate)
     736            0 :     return option.success ? [option.data] : []
     737              :   })
     738              : }
     739              : 
     740            0 : function optionChildSpecs(option: {
     741              :   inputs: ComfyInputsSpec
     742              : }): [string, InputSpecV2][] {
     743            0 :   const { required, optional } = option.inputs
     744            0 :   return Object.entries({ ...required, ...optional }).map(([key, child]) => [
     745              :     key,
     746              :     transformInputSpecV1ToV2(child, { name: key })
     747              :   ])
     748              : }
     749              : 
     750            0 : function collectOptionOwnedBranches(
     751              :   selector: string,
     752              :   combo: { options: readonly unknown[] },
     753              :   gates: readonly OptionGate[],
     754              :   branches: OptionOwnedBranch[],
     755              :   depth: number
     756              : ): void {
     757            0 :   if (depth >= MAX_OPTION_NESTING) return
     758            0 :   for (const option of comboOptions(combo)) {
     759            0 :     const optionGates = [...gates, { selector, optionKey: option.key }]
     760            0 :     for (const [key, spec] of optionChildSpecs(option)) {
     761            0 :       const prefix = `${selector}.${key}`
     762            0 :       branches.push({ prefix, gates: optionGates })
     763            0 :       const nested = zDynamicComboSpecV2.safeParse(spec)
     764            0 :       if (nested.success)
     765            0 :         collectOptionOwnedBranches(
     766              :           prefix,
     767              :           nested.data,
     768              :           optionGates,
     769              :           branches,
     770              :           depth + 1
     771              :         )
     772              :     }
     773              :   }
     774              : }
     775              : 
     776            0 : function widestOptionWidgetCount(
     777              :   combo: { options: readonly unknown[] },
     778              :   depth: number
     779              : ): number {
     780            0 :   if (depth >= MAX_OPTION_NESTING) return Number.POSITIVE_INFINITY
     781            0 :   let widest = 0
     782            0 :   for (const option of comboOptions(combo)) {
     783            0 :     let width = 0
     784            0 :     for (const [, spec] of optionChildSpecs(option)) {
     785            0 :       const nested = zDynamicComboSpecV2.safeParse(spec)
     786            0 :       if (nested.success)
     787            0 :         width += 1 + widestOptionWidgetCount(nested.data, depth + 1)
     788            0 :       else if (VARIABLE_LENGTH_CONTROL_TYPES.has(spec.type))
     789            0 :         return Number.POSITIVE_INFINITY
     790            0 :       else width += 1
     791              :     }
     792            0 :     widest = Math.max(widest, width)
     793              :   }
     794            0 :   return widest
     795              : }
     796              : 
     797            1 : const OVERFLOW_WIDGET_NAME_RE = /^_extra_(0|[1-9]\d*)$/
     798              : 
     799            0 : function overflowWidgetIndex(name: string): number | null {
     800            0 :   const match = OVERFLOW_WIDGET_NAME_RE.exec(name)
     801            0 :   return match ? Number(match[1]) : null
     802              : }
     803              : 
     804              : type OptionOwnership = 'selectedOption' | 'unselectedOption' | 'noOption'
     805              : 
     806            1 : const OWNERSHIP_PRECEDENCE: Record<OptionOwnership, number> = {
     807              :   noOption: 0,
     808              :   unselectedOption: 1,
     809              :   selectedOption: 2
     810              : }
     811              : 
     812            0 : function liveSelectedOptionKey(
     813              :   node: LGraphNode,
     814              :   selector: string
     815              : ): string | undefined {
     816            0 :   const value = node.widgets?.find(({ name }) => name === selector)?.value
     817            0 :   return typeof value === 'string' ? value : undefined
     818              : }
     819              : 
     820            0 : function branchOwnership(
     821              :   node: LGraphNode,
     822              :   branch: OptionOwnedBranch
     823              : ): OptionOwnership {
     824            0 :   for (const { selector, optionKey } of branch.gates) {
     825            0 :     const selected = liveSelectedOptionKey(node, selector)
     826            0 :     if (selected === undefined) return 'noOption'
     827            0 :     if (selected !== optionKey) return 'unselectedOption'
     828              :   }
     829            0 :   return 'selectedOption'
     830              : }
     831              : 
     832            0 : function optionOwnership(node: LGraphNode, name: string): OptionOwnership {
     833            0 :   let longestPrefix = -1
     834            0 :   let ownership: OptionOwnership = 'noOption'
     835            0 :   for (const branch of optionLayout(node).branches) {
     836            0 :     if (name !== branch.prefix && !name.startsWith(`${branch.prefix}.`))
     837            0 :       continue
     838            0 :     const { length } = branch.prefix
     839            0 :     if (length < longestPrefix) continue
     840            0 :     const verdict = branchOwnership(node, branch)
     841            0 :     if (length > longestPrefix) {
     842            0 :       longestPrefix = length
     843            0 :       ownership = verdict
     844            0 :     } else if (OWNERSHIP_PRECEDENCE[verdict] > OWNERSHIP_PRECEDENCE[ownership])
     845            0 :       ownership = verdict
     846              :   }
     847            0 :   return ownership
     848              : }
     849              : 
     850            0 : function widestSelectionWidgetCount(node: LGraphNode): number {
     851            0 :   const widgets = serializableWidgets(node)
     852            0 :   return optionLayout(node).selectors.reduce(
     853              :     (total, { name, widestOptionWidgetCount: widest }) =>
     854              :       total +
     855              :       Math.max(
     856              :         0,
     857              :         widest -
     858              :           widgets.filter(({ name: widget }) => widget.startsWith(`${name}.`))
     859              :             .length
     860              :       ),
     861              :     widgets.length
     862              :   )
     863              : }
     864              : 
     865            0 : function selectionDependentAbsence(node: LGraphNode, name: string): boolean {
     866            0 :   const index = overflowWidgetIndex(name)
     867            0 :   return index === null
     868              :     ? optionOwnership(node, name) === 'unselectedOption'
     869              :     : index < widestSelectionWidgetCount(node)
     870              : }
     871              : 
     872            0 : function documentWidget(
     873              :   node: LGraphNode,
     874              :   name: string
     875              : ): IBaseWidget | undefined {
     876            0 :   return (
     877              :     node.widgets?.find((widget) => widget.name === name) ??
     878              :     overflowWidget(node, name)
     879              :   )
     880              : }
     881              : 
     882              : /** The live widget an overflow alias addresses, if the node has that position. */
     883            0 : function overflowWidget(
     884              :   node: LGraphNode,
     885              :   name: string
     886              : ): IBaseWidget | undefined {
     887            0 :   const overflowIndex = overflowWidgetIndex(name)
     888            0 :   return overflowIndex === null
     889              :     ? undefined
     890              :     : serializableWidgets(node).at(overflowIndex)
     891              : }
     892              : 
     893              : /**
     894              :  * Whether `name` is an overflow alias for a position the document also
     895              :  * addresses by the live widget's real name; the named entry wins. Judged
     896              :  * against the node's whole document map so an alias-only partial frame cannot
     897              :  * overwrite the named value.
     898              :  */
     899            0 : function supersededOverflowAlias(
     900              :   node: LGraphNode,
     901              :   name: string,
     902              :   document: DocNode['widgets']
     903              : ): boolean {
     904            0 :   if (document === undefined || Array.isArray(document)) return false
     905            0 :   if (node.widgets?.some((widget) => widget.name === name)) return false
     906            0 :   const positional = overflowWidget(node, name)
     907            0 :   return positional !== undefined && Object.hasOwn(document, positional.name)
     908              : }
     909              : 
     910            0 : function closestController(
     911              :   node: LGraphNode,
     912              :   name: string
     913              : ): IBaseWidget | undefined {
     914            0 :   let controller: IBaseWidget | undefined
     915            0 :   for (const widget of node.widgets ?? []) {
     916            0 :     if (!isDynamicGroupController(widget)) continue
     917            0 :     if (!name.startsWith(`${widget.name}.`)) continue
     918            0 :     if (!controller || widget.name.length > controller.name.length)
     919            0 :       controller = widget
     920              :   }
     921            0 :   return controller
     922              : }
     923              : 
     924            0 : function hiddenRowController(
     925              :   node: LGraphNode,
     926              :   name: string
     927              : ): IBaseWidget | undefined {
     928            0 :   const controller = closestController(node, name)
     929            0 :   if (!controller) return undefined
     930            0 :   const [index, ...field] = name.slice(controller.name.length + 1).split('.')
     931            0 :   if (!/^(0|[1-9]\d*)$/.test(index) || !field.length || !field.every(Boolean))
     932            0 :     return undefined
     933            0 :   const count = controller.value
     934            0 :   return typeof count === 'number' && Number(index) >= count
     935              :     ? controller
     936              :     : undefined
     937              : }
     938              : 
     939            0 : function regrownRow(
     940              :   node: LGraphNode,
     941              :   name: string,
     942              :   names: ReadonlySet<string>
     943              : ): boolean {
     944            0 :   const controller = hiddenRowController(node, name)
     945            0 :   return controller !== undefined && names.has(controller.name)
     946              : }
     947              : 
     948            0 : function deferredRowCounts(
     949              :   node: LGraphNode,
     950              :   constructed: readonly IBaseWidget[],
     951              :   widgets: DocNode['widgets']
     952              : ): ReadonlySet<string> {
     953            0 :   if (
     954              :     widgets === undefined ||
     955              :     Array.isArray(widgets) ||
     956              :     supportsDynamicWidgetOverflow(node)
     957              :   )
     958            0 :     return new Set()
     959            0 :   return new Set(
     960              :     constructed
     961              :       .filter(
     962              :         (widget) =>
     963              :           isDynamicGroupController(widget) &&
     964              :           Object.hasOwn(widgets, widget.name)
     965              :       )
     966              :       .map((widget) => widget.name)
     967              :   )
     968              : }
     969              : 
     970              : /**
     971              :  * Document entries for widgets that only exist after `configure`: aliases past
     972              :  * the constructed list, and names the constructor did not build but the node
     973              :  * now serializes. `constructed` is the serializable list from before
     974              :  * `configure`; a name that still matches nothing is dropped without a report.
     975              :  */
     976            0 : function mountedWidgetValues(
     977              :   node: LGraphNode,
     978              :   widgets: DocNode['widgets'],
     979              :   constructed: readonly IBaseWidget[],
     980              :   constructedNames: ReadonlySet<string>,
     981              :   deferred: ReadonlySet<string>
     982              : ): Record<string, unknown> | undefined {
     983            0 :   if (widgets === undefined || Array.isArray(widgets)) return undefined
     984            0 :   const mounted = Object.entries(widgets).filter(([name]) => {
     985            0 :     const index = overflowWidgetIndex(name)
     986            0 :     return index === null
     987              :       ? !constructedNames.has(name) || deferred.has(name)
     988              :       : overflowWidget(node, name) === undefined || index >= constructed.length
     989              :   })
     990            0 :   return mounted.length === 0 ? undefined : Object.fromEntries(mounted)
     991              : }
     992              : 
     993              : /**
     994              :  * The document stores an ordinary node's widget values by name; `configure`
     995              :  * restores them positionally over the node's serializable widgets, so project
     996              :  * the named map into that order, keeping the constructor default for any
     997              :  * widget the document does not mention.
     998              :  */
     999            0 : function positionalWidgetValues(
    1000              :   node: LGraphNode,
    1001              :   widgets: DocNode['widgets'],
    1002              :   deferred: ReadonlySet<string>
    1003              : ): WidgetValue[] | undefined {
    1004            0 :   if (widgets === undefined) return undefined
    1005            0 :   if (Array.isArray(widgets)) {
    1006            0 :     return widgets.map((value): WidgetValue =>
    1007              :       isWidgetValue(value) ? value : undefined
    1008              :     )
    1009              :   }
    1010            0 :   return serializableWidgets(node).map((widget, index) => {
    1011            0 :     if (deferred.has(widget.name)) return widget.value
    1012            0 :     const alias = `_extra_${index}`
    1013            0 :     const name = Object.hasOwn(widgets, widget.name)
    1014              :       ? widget.name
    1015              :       : overflowWidget(node, alias) === widget && Object.hasOwn(widgets, alias)
    1016              :         ? alias
    1017              :         : widget.name
    1018            0 :     const value = widgets[name]
    1019            0 :     return Object.hasOwn(widgets, name) && isWidgetValue(value)
    1020              :       ? value
    1021              :       : widget.value
    1022              :   })
    1023              : }
    1024              : 
    1025            0 : function addGroup(graph: LGraph, serialised: ISerialisedGroup): LGraphGroup {
    1026            0 :   const group = new LGraphGroup()
    1027            0 :   group.configure(serialised)
    1028            0 :   graph.add(group)
    1029            0 :   return group
    1030              : }
    1031              : 
    1032            0 : function missingNode(docNode: DocNode): LGraphNode {
    1033            0 :   const node = new LGraphNode(
    1034              :     docNode.serialised.title || docNode.type || 'Missing Node',
    1035              :     docNode.type
    1036              :   )
    1037            0 :   node.has_errors = true
    1038            0 :   return node
    1039              : }
    1040              : 
    1041              : /**
    1042              :  * A document may carry a size smaller than the node's widgets need (or none
    1043              :  * at all). Every human path — `loadGraphData`, which the undo stack restores
    1044              :  * through, and interactive resize — floors the size at `computeSize()`, so a
    1045              :  * node born below that floor snapshots at one size and restores at another,
    1046              :  * which the change tracker then records as a fresh edit.
    1047              :  */
    1048            0 : function floorSizeToContent(node: LGraphNode): void {
    1049            0 :   const [minWidth, minHeight] = node.computeSize()
    1050            0 :   const [width, height] = node.size
    1051            0 :   if (width >= minWidth && height >= minHeight) return
    1052            0 :   node.setSize([Math.max(width, minWidth), Math.max(height, minHeight)])
    1053              : }
    1054              : 
    1055            0 : function configureRemoteNode(node: LGraphNode, info: ISerialisedNode): void {
    1056            0 :   applyRemoteDynamicGroupRowCount(node, () => node.configure(info))
    1057              : }
    1058              : 
    1059            0 : function widgetAcceptedValue(widget: IBaseWidget, value: WidgetValue): boolean {
    1060            0 :   return (
    1061              :     !isDynamicGroupController(widget) ||
    1062              :     reachesDynamicGroupRowCount(widget, value)
    1063              :   )
    1064              : }
    1065              : 
    1066            1 : export class LiveGraphApplier {
    1067              :   private readonly deps: LiveGraphApplierDeps
    1068              :   private readonly reported = new Set<string>()
    1069              :   private readonly interiorIds = new Map<string, Map<string, NodeId>>()
    1070              :   private readonly failureCounts: number[] = []
    1071              :   private readonly unappliedRegrownRows = new WeakMap<
    1072              :     LGraphNode,
    1073              :     ReadonlySet<string>
    1074              :   >()
    1075              : 
    1076              :   constructor(deps: LiveGraphApplierDeps) {
    1077            1 :     this.deps = deps
    1078              :   }
    1079              : 
    1080              :   /** Applies the collected changes of one delivered frame to the live graph. */
    1081              :   applyChanges(
    1082              :     doc: Y.Doc,
    1083              :     changes: FrameChanges,
    1084              :     context: RemoteApplyContext,
    1085              :     mode: ApplyMode = 'merge'
    1086              :   ): ApplyResult {
    1087            0 :     const graph = this.deps.getGraph()
    1088            0 :     if (!graph) return { createdNodeIds: [], failureCount: 0 }
    1089            0 :     this.failureCounts.push(0)
    1090            0 :     try {
    1091            0 :       return this.write(graph, context, () => {
    1092            0 :         if (mode === 'replace') this.removeAbsent(graph, doc, context)
    1093            0 :         const created: NodeId[] = []
    1094            0 :         const touchedNodes = new Set<string>()
    1095            0 :         this.registerDefinitions(graph, doc)
    1096              : 
    1097            0 :         for (const [id, change] of changes.nodes) {
    1098            0 :           if (change === 'delete') {
    1099            0 :             this.try(context, () => this.deleteNode(graph, id))
    1100            0 :             continue
    1101              :           }
    1102            0 :           touchedNodes.add(id)
    1103            0 :           this.try(context, () => {
    1104            0 :             const result = this.upsertNode(graph, doc, id, mode, context)
    1105            0 :             if (result === 'created') created.push(toNodeId(id))
    1106            0 :             if (result === 'created' || result === 'recreated') {
    1107            0 :               for (const link of docLinksIncident(doc, id)) {
    1108            0 :                 this.connectLink(graph, doc, link)
    1109              :               }
    1110              :             }
    1111              :           })
    1112              :         }
    1113              : 
    1114            0 :         for (const [id, keys] of changes.resyncNodes) {
    1115            0 :           if (touchedNodes.has(id)) continue
    1116            0 :           this.try(context, () => this.syncFields(graph, doc, id, keys))
    1117              :         }
    1118              : 
    1119            0 :         for (const [id, names] of changes.widgets) {
    1120            0 :           if (touchedNodes.has(id)) continue
    1121            0 :           this.try(context, () => this.syncWidgets(graph, doc, id, names, mode))
    1122              :         }
    1123              : 
    1124            0 :         this.applyInteriors(graph, doc, changes, context, mode)
    1125              : 
    1126            0 :         this.applyLinks(graph, doc, [...changes.links], context)
    1127            0 :         const createdGroups = this.applyGroups(
    1128              :           graph,
    1129              :           doc,
    1130              :           changes.groups,
    1131              :           context
    1132              :         )
    1133            0 :         if (mode === 'merge')
    1134            0 :           this.placeBatch(graph, created, createdGroups, {
    1135              :             moveCollisions: context.liveAgentTurn === true
    1136              :           })
    1137            0 :         return {
    1138              :           createdNodeIds: created,
    1139              :           failureCount: this.currentFailureCount()
    1140              :         }
    1141              :       })
    1142              :     } finally {
    1143            0 :       this.failureCounts.pop()
    1144              :     }
    1145              :   }
    1146              : 
    1147              :   private removeAbsent(
    1148              :     graph: LGraph,
    1149              :     doc: Y.Doc,
    1150              :     context: RemoteApplyContext
    1151              :   ): void {
    1152            0 :     const docNodes = nodesMap(doc)
    1153            0 :     const absentNodes = graph._nodes.filter(
    1154              :       (node) => !docNodes.has(String(node.id))
    1155              :     )
    1156            0 :     for (const node of absentNodes) {
    1157            0 :       this.try(context, () => graph.remove(node))
    1158              :     }
    1159            0 :     const docLinks = linksMap(doc)
    1160            0 :     for (const id of graph.links.keys()) {
    1161            0 :       if (docLinks.has(String(id))) continue
    1162            0 :       this.try(context, () => graph.removeLink(id))
    1163              :     }
    1164            0 :     const docGroups = readDocGroups(doc.getMap<unknown>('meta').get('groups'))
    1165            0 :     const absentGroups = graph.groups.filter(
    1166              :       (group) => !docGroups.has(String(group.id))
    1167              :     )
    1168            0 :     for (const group of absentGroups) {
    1169            0 :       this.try(context, () => graph.remove(group))
    1170              :     }
    1171              :   }
    1172              : 
    1173              :   private write<T>(graph: LGraph, context: RemoteApplyContext, fn: () => T): T {
    1174              :     const withActor = this.deps.withRemoteActor ?? ((_, run) => run())
    1175            0 :     return withActor(context.actor, () => {
    1176            0 :       const canvas = this.deps.getCanvas?.()
    1177            0 :       canvas?.emitBeforeChange()
    1178            0 :       try {
    1179            0 :         return withLiveAgentTurnWrites(
    1180              :           { isLiveAgentTurn: context.liveAgentTurn === true },
    1181              :           () => withGraphIntentSource('agent-remote', fn)
    1182              :         )
    1183              :       } finally {
    1184            0 :         if (canvas) canvas.setDirty(true, true)
    1185            0 :         else graph.setDirtyCanvas(true, true)
    1186            0 :         canvas?.emitAfterChange()
    1187              :       }
    1188              :     })
    1189              :   }
    1190              : 
    1191              :   private try(context: RemoteApplyContext, fn: () => void): void {
    1192            0 :     try {
    1193            0 :       fn()
    1194              :     } catch (error) {
    1195            0 :       this.incrementFailureCount()
    1196            0 :       reportError(error, {
    1197              :         surface: 'agent',
    1198              :         errorType: 'agent_graph_apply_failed',
    1199              :         tags: { ...AGENT_APPLY_TAGS, outcome: 'degraded' },
    1200              :         context: diagnosticApplyContext(context)
    1201              :       })
    1202              :     }
    1203              :   }
    1204              : 
    1205              :   private reportOnce(
    1206              :     key: string,
    1207              :     message: string,
    1208              :     errorType: string,
    1209              :     context: Record<string, unknown>,
    1210              :     cause?: unknown
    1211              :   ): void {
    1212            0 :     this.incrementFailureCount()
    1213            0 :     if (this.reported.has(key)) return
    1214            0 :     this.reported.add(key)
    1215            0 :     reportError(
    1216              :       cause === undefined ? new Error(message) : new Error(message, { cause }),
    1217              :       {
    1218              :         surface: 'agent',
    1219              :         errorType,
    1220              :         tags: { ...AGENT_APPLY_TAGS, outcome: 'degraded' },
    1221              :         context: boundedContext(context)
    1222              :       }
    1223              :     )
    1224              :   }
    1225              : 
    1226              :   private currentFailureCount(): number {
    1227            0 :     return this.failureCounts.at(-1) ?? 0
    1228              :   }
    1229              : 
    1230              :   private incrementFailureCount(): void {
    1231            0 :     const index = this.failureCounts.length - 1
    1232            0 :     if (index >= 0) this.failureCounts[index] += 1
    1233              :   }
    1234              : 
    1235              :   private registerDefinitions(graph: LGraph, doc: Y.Doc): void {
    1236            0 :     const rootGraph = graph.rootGraph
    1237            0 :     const missing = allSubgraphDefinitions(readSubgraphDefinitions(doc))
    1238              :       .map((definition) => ({ ...definition, definitions: undefined }))
    1239              :       .filter((definition) => !rootGraph.subgraphs.has(definition.id))
    1240            0 :     if (missing.length === 0) return
    1241            0 :     const reserved = docRootIds(doc)
    1242            0 :     for (const definition of topologicalSortSubgraphs(missing)) {
    1243            0 :       const failure = tryCreateSubgraph(rootGraph, definition, reserved)
    1244            0 :       if (failure === undefined) {
    1245            0 :         this.reported.delete(`definition:${definition.id}`)
    1246            0 :         this.recordInteriorIds(rootGraph, definition)
    1247            0 :         continue
    1248              :       }
    1249            0 :       this.incrementFailureCount()
    1250            0 :       if (this.reported.has(`definition:${definition.id}`)) continue
    1251            0 :       this.reported.add(`definition:${definition.id}`)
    1252            0 :       reportError(failure, {
    1253              :         surface: 'agent',
    1254              :         errorType: 'agent_subgraph_definitions_failed',
    1255              :         tags: { ...AGENT_APPLY_TAGS, outcome: 'degraded' },
    1256              :         context: { graphId: graph.id, definitionId: definition.id }
    1257              :       })
    1258              :     }
    1259              :   }
    1260              : 
    1261              :   private recordInteriorIds(
    1262              :     rootGraph: LGraph,
    1263              :     definition: ExportedSubgraph
    1264              :   ): void {
    1265            0 :     const live = rootGraph.subgraphs.get(definition.id)
    1266            0 :     if (!live || !definition.nodes) return
    1267            0 :     this.recordInteriorMapping(
    1268              :       definition.id,
    1269              :       definition.nodes.map((node) => String(node.id)),
    1270              :       live.nodes
    1271              :     )
    1272              :   }
    1273              : 
    1274              :   private recordInteriorMapping(
    1275              :     definitionId: string,
    1276              :     orderedDocIds: readonly string[],
    1277              :     liveNodes: readonly LGraphNode[]
    1278              :   ): void {
    1279            0 :     if (orderedDocIds.length !== liveNodes.length) return
    1280            0 :     const mapping = new Map<string, NodeId>()
    1281            0 :     for (const [index, docId] of orderedDocIds.entries()) {
    1282            0 :       mapping.set(docId, liveNodes[index].id)
    1283              :     }
    1284            0 :     this.interiorIds.set(definitionId, mapping)
    1285              :   }
    1286              : 
    1287              :   private deleteNode(graph: LGraph, id: string): void {
    1288            0 :     const node = graph.getNodeById(toNodeId(id))
    1289            0 :     if (node) graph.remove(node)
    1290              :   }
    1291              : 
    1292              :   private applyGroups(
    1293              :     graph: LGraph,
    1294              :     doc: Y.Doc,
    1295              :     ids: ReadonlySet<string> | undefined,
    1296              :     context: RemoteApplyContext
    1297              :   ): LGraphGroup[] {
    1298            0 :     if (!ids?.size) return []
    1299            0 :     const docGroups = readDocGroups(doc.getMap<unknown>('meta').get('groups'))
    1300            0 :     const created: LGraphGroup[] = []
    1301            0 :     for (const id of ids) {
    1302            0 :       this.try(context, () => {
    1303            0 :         const live = graph.groups.find((group) => String(group.id) === id)
    1304            0 :         const docGroup = docGroups.get(id)
    1305            0 :         if (live && !docGroup) graph.remove(live)
    1306            0 :         else if (!live && docGroup) created.push(addGroup(graph, docGroup))
    1307              :       })
    1308              :     }
    1309            0 :     return created
    1310              :   }
    1311              : 
    1312              :   private upsertNode(
    1313              :     graph: LGraph,
    1314              :     doc: Y.Doc,
    1315              :     id: string,
    1316              :     mode: ApplyMode,
    1317              :     context: RemoteApplyContext
    1318              :   ): 'created' | 'recreated' | 'updated' | 'skipped' {
    1319            0 :     const docNode = this.readDocNode(doc, id)
    1320            0 :     if (!docNode) return 'skipped'
    1321            0 :     const live = graph.getNodeById(toNodeId(id))
    1322            0 :     if (live && live.type === docNode.type) {
    1323            0 :       this.applyFields(live, docNode)
    1324            0 :       if (docNode.widgetRecord) restoreWidgetRecord(live, docNode.widgetRecord)
    1325            0 :       else this.applyWidgets(live, docNode.widgets, mode)
    1326            0 :       return 'updated'
    1327              :     }
    1328            0 :     if (live) graph.remove(live)
    1329            0 :     this.createNode(graph, docNode, mode, context)
    1330            0 :     return live ? 'recreated' : 'created'
    1331              :   }
    1332              : 
    1333              :   private createNode(
    1334              :     graph: LGraph,
    1335              :     docNode: DocNode,
    1336              :     mode: ApplyMode,
    1337              :     context: RemoteApplyContext
    1338              :   ): LGraphNode {
    1339            0 :     const node =
    1340              :       LiteGraph.createNode(docNode.type, docNode.serialised.title) ??
    1341              :       missingNode(docNode)
    1342            0 :     node.id = toNodeId(docNode.id)
    1343            0 :     const info: ISerialisedNode = {
    1344              :       ...docNode.serialised,
    1345              :       inputs: docNode.serialised.inputs?.map(
    1346              :         (input): ISerialisableNodeInput => ({ ...input })
    1347              :       ),
    1348              :       outputs: docNode.serialised.outputs?.map(
    1349              :         (output): ISerialisableNodeOutput => ({ ...output })
    1350              :       )
    1351              :     }
    1352            0 :     if (docNode.widgetRecord)
    1353            0 :       info.widgets_values = docNode.widgetRecord as unknown as WidgetValue[]
    1354            0 :     detachSerialisedLinks(info)
    1355            0 :     node.pos = [info.pos[0], info.pos[1]]
    1356            0 :     graph.add(node)
    1357            0 :     if (node.id !== toNodeId(docNode.id)) {
    1358            0 :       const existingOwner = diagnosticNodeOwner(graph, toNodeId(docNode.id))
    1359            0 :       this.reportOnce(
    1360              :         `node-id:${docNode.id}`,
    1361              :         `Live graph reminted node ${docNode.id} as ${String(node.id)}`,
    1362              :         'agent_graph_node_id_reminted',
    1363              :         {
    1364              :           nodeId: docNode.id,
    1365              :           liveId: node.id,
    1366              :           nodeType: docNode.type,
    1367              :           mode,
    1368              :           ...existingOwner,
    1369              :           ...diagnosticApplyContext(context),
    1370              :           liveAgentTurn: context.liveAgentTurn === true
    1371              :         }
    1372              :       )
    1373              :     }
    1374            0 :     if (node.has_errors) {
    1375            0 :       node.last_serialization = info
    1376            0 :       configureRemoteNode(node, info)
    1377              :     } else {
    1378            0 :       if (node.isSubgraphNode()) {
    1379            0 :         const beforeConfigurePromotedIds = promotedWidgetIds(node)
    1380            0 :         configureRemoteNode(node, info)
    1381            0 :         this.applyConfiguredHostWidgets(
    1382              :           node,
    1383              :           docNode.widgets,
    1384              :           beforeConfigurePromotedIds,
    1385              :           mode
    1386              :         )
    1387              :       } else {
    1388            0 :         const constructed = serializableWidgets(node)
    1389            0 :         const constructedNames = new Set(
    1390              :           node.widgets?.map((widget) => widget.name)
    1391              :         )
    1392            0 :         const deferred = deferredRowCounts(node, constructed, docNode.widgets)
    1393            0 :         configureRemoteNode(node, {
    1394              :           ...info,
    1395              :           widgets_values:
    1396              :             docNode.widgetRecord === undefined
    1397              :               ? positionalWidgetValues(node, docNode.widgets, deferred)
    1398              :               : info.widgets_values
    1399              :         })
    1400            0 :         const mounted = mountedWidgetValues(
    1401              :           node,
    1402              :           docNode.widgets,
    1403              :           constructed,
    1404              :           constructedNames,
    1405              :           deferred
    1406              :         )
    1407            0 :         if (mounted)
    1408            0 :           this.applyWidgets(node, mounted, mode, {
    1409              :             documentWidgets: docNode.widgets,
    1410              :             reportMissing: false
    1411              :           })
    1412              :       }
    1413              :     }
    1414            0 :     floorSizeToContent(node)
    1415            0 :     return node
    1416              :   }
    1417              : 
    1418              :   private applyFields(
    1419              :     node: LGraphNode,
    1420              :     docNode: DocNode,
    1421              :     keys?: ReadonlySet<string>
    1422              :   ): void {
    1423            0 :     const source = docNode.serialised
    1424            0 :     const edited = (key: string): boolean => !keys || keys.has(key)
    1425            0 :     const flagsEdited =
    1426              :       !keys ||
    1427              :       keys.has('flags') ||
    1428              :       [...keys].some((key) => key.startsWith('flags.'))
    1429            0 :     if (
    1430              :       edited('title') &&
    1431              :       source.title !== undefined &&
    1432              :       node.title !== source.title
    1433              :     )
    1434            0 :       node.title = source.title
    1435            0 :     if (edited('mode')) this.applyMode(node, docNode)
    1436            0 :     if (flagsEdited) applyFlags(node, source.flags, keys)
    1437            0 :     if (edited('properties')) applyProperties(node, source.properties)
    1438            0 :     applyAppearance(node, source, edited)
    1439              :   }
    1440              : 
    1441              :   private applyMode(node: LGraphNode, docNode: DocNode): void {
    1442            0 :     const { mode } = docNode.serialised
    1443            0 :     if (node.mode === mode || node.changeMode(mode)) return
    1444            0 :     this.reportOnce(
    1445              :       `node-mode:${docNode.id}:${mode}`,
    1446              :       `Document node ${docNode.id} rejected mode ${mode}`,
    1447              :       'agent_graph_node_mode_rejected',
    1448              :       { nodeId: docNode.id, mode }
    1449              :     )
    1450              :   }
    1451              : 
    1452              :   private readDocNode(doc: Y.Doc, id: string): DocNode | null {
    1453            0 :     const read = readDocNode(doc, id)
    1454            0 :     if (read === null) return null
    1455            0 :     const key = `node-shape:${id}`
    1456            0 :     if (!('malformed' in read)) {
    1457            0 :       this.reported.delete(key)
    1458            0 :       return read
    1459              :     }
    1460            0 :     if (this.reported.has(key)) return null
    1461            0 :     const { classType, valueShapes, producer } = read.discriminate()
    1462            0 :     this.reportOnce(
    1463              :       key,
    1464              :       `Document node ${id} (${classType ?? 'unknown class'}) is malformed: ${read.malformed}`,
    1465              :       'agent_graph_node_malformed',
    1466              :       { nodeId: id, issues: read.malformed, classType, valueShapes, producer }
    1467              :     )
    1468            0 :     return null
    1469              :   }
    1470              : 
    1471              :   private syncFields(
    1472              :     graph: LGraph,
    1473              :     doc: Y.Doc,
    1474              :     id: string,
    1475              :     keys: ReadonlySet<string>
    1476              :   ): void {
    1477            0 :     const docNode = this.readDocNode(doc, id)
    1478            0 :     const node = graph.getNodeById(toNodeId(id))
    1479            0 :     if (!docNode || !node || node.type !== docNode.type) return
    1480            0 :     this.applyFields(node, docNode, keys)
    1481              :   }
    1482              : 
    1483              :   private syncWidgets(
    1484              :     graph: LGraph,
    1485              :     doc: Y.Doc,
    1486              :     id: string,
    1487              :     names: ReadonlySet<string> | 'all',
    1488              :     mode: ApplyMode
    1489              :   ): void {
    1490            0 :     const docNode = this.readDocNode(doc, id)
    1491            0 :     const node = graph.getNodeById(toNodeId(id))
    1492            0 :     if (!docNode || !node || node.type !== docNode.type) return
    1493            0 :     if (docNode.widgetRecord) {
    1494            0 :       restoreWidgetRecord(node, docNode.widgetRecord)
    1495            0 :       return
    1496              :     }
    1497            0 :     const widgets = docNode.widgets
    1498            0 :     if (names === 'all' || Array.isArray(widgets)) {
    1499            0 :       this.applyWidgets(node, widgets, mode)
    1500            0 :       return
    1501              :     }
    1502            0 :     if (!widgets) return
    1503            0 :     const regrown = this.regrownRows(node, Object.keys(widgets), names)
    1504            0 :     this.applyWidgets(
    1505              :       node,
    1506              :       Object.fromEntries(
    1507              :         Object.entries(widgets).filter(
    1508              :           ([name]) => changed(node, name, names) || regrown.has(name)
    1509              :         )
    1510              :       ),
    1511              :       mode,
    1512              :       { documentWidgets: widgets }
    1513              :     )
    1514              :   }
    1515              : 
    1516              :   private regrownRows(
    1517              :     node: LGraphNode,
    1518              :     keys: readonly string[],
    1519              :     names: ReadonlySet<string>
    1520              :   ): ReadonlySet<string> {
    1521            0 :     const regrown = new Set(this.unappliedRegrownRows.get(node))
    1522            0 :     for (const name of keys) {
    1523            0 :       if (regrownRow(node, name, names)) regrown.add(name)
    1524              :     }
    1525            0 :     if (regrown.size > 0) this.unappliedRegrownRows.set(node, regrown)
    1526            0 :     return regrown
    1527              :   }
    1528              : 
    1529              :   private applyInteriors(
    1530              :     graph: LGraph,
    1531              :     doc: Y.Doc,
    1532              :     changes: FrameChanges,
    1533              :     context: RemoteApplyContext,
    1534              :     mode: ApplyMode
    1535              :   ): void {
    1536            0 :     const granular = changes.interiors
    1537            0 :     const full = changes.interiorDefinitions
    1538            0 :     const hasGranular = granular !== undefined && granular.size > 0
    1539            0 :     const hasFull = full !== undefined && full.size > 0
    1540            0 :     if (!hasGranular && !hasFull) return
    1541            0 :     const docInteriors = readSubgraphInteriorWidgets(doc)
    1542            0 :     const targets = interiorSyncTargets(granular, full, docInteriors)
    1543            0 :     for (const [definitionId, nodes] of targets) {
    1544            0 :       this.try(context, () =>
    1545              :         this.syncDefinitionInteriors(
    1546              :           graph,
    1547              :           definitionId,
    1548              :           nodes,
    1549              :           docInteriors,
    1550              :           mode
    1551              :         )
    1552              :       )
    1553              :     }
    1554              :   }
    1555              : 
    1556              :   private syncDefinitionInteriors(
    1557              :     graph: LGraph,
    1558              :     definitionId: string,
    1559              :     nodes: ReadonlyMap<string, ReadonlySet<string> | 'all'>,
    1560              :     docInteriors: ReturnType<typeof readSubgraphInteriorWidgets>,
    1561              :     mode: ApplyMode
    1562              :   ): void {
    1563            0 :     const subgraph = graph.rootGraph.subgraphs.get(definitionId)
    1564            0 :     if (!subgraph) return
    1565            0 :     const docNodes = docInteriors.get(definitionId)
    1566            0 :     if (!docNodes) return
    1567            0 :     if (!this.interiorIds.has(definitionId)) {
    1568            0 :       this.recordInteriorMapping(
    1569              :         definitionId,
    1570              :         [...docNodes.keys()],
    1571              :         subgraph.nodes
    1572              :       )
    1573              :     }
    1574            0 :     for (const [nodeId, names] of nodes) {
    1575            0 :       const widgets = docNodes.get(nodeId)
    1576            0 :       if (widgets === undefined) continue
    1577            0 :       const mapped = this.interiorIds.get(definitionId)?.get(nodeId)
    1578            0 :       const live = mapped
    1579              :         ? subgraph.getNodeById(mapped)
    1580              :         : subgraph.getNodeById(toNodeId(nodeId))
    1581            0 :       if (!live) continue
    1582            0 :       this.applyInteriorWidgets(live, widgets, names, mode)
    1583            0 :       this.propagateInteriorToHosts(
    1584              :         graph,
    1585              :         definitionId,
    1586              :         live,
    1587              :         widgets,
    1588              :         names,
    1589              :         mode
    1590              :       )
    1591              :     }
    1592              :   }
    1593              : 
    1594              :   private propagateInteriorToHosts(
    1595              :     graph: LGraph,
    1596              :     definitionId: string,
    1597              :     liveInterior: LGraphNode,
    1598              :     widgets: unknown,
    1599              :     names: ReadonlySet<string> | 'all',
    1600              :     mode: ApplyMode
    1601              :   ): void {
    1602            0 :     if (names === 'all') return
    1603            0 :     if (widgets === undefined || Array.isArray(widgets)) return
    1604            0 :     const record = widgets as Record<string, unknown>
    1605            0 :     for (const host of subgraphHostInstances(graph, definitionId)) {
    1606            0 :       this.propagateInteriorToHost(host, liveInterior, record, names, mode)
    1607              :     }
    1608              :   }
    1609              : 
    1610              :   private applyInteriorWidgets(
    1611              :     live: LGraphNode,
    1612              :     widgets: Record<string, unknown> | readonly unknown[],
    1613              :     names: ReadonlySet<string> | 'all',
    1614              :     mode: ApplyMode
    1615              :   ): void {
    1616            0 :     if (names === 'all' || Array.isArray(widgets)) {
    1617            0 :       this.applyWidgets(live, widgets as DocNode['widgets'], mode)
    1618            0 :       return
    1619              :     }
    1620            0 :     const regrown = this.regrownRows(live, Object.keys(widgets), names)
    1621            0 :     const filtered = Object.fromEntries(
    1622              :       Object.entries(widgets).filter(
    1623              :         ([name]) => names.has(name) || regrown.has(name)
    1624              :       )
    1625              :     )
    1626            0 :     if (Object.keys(filtered).length === 0) return
    1627            0 :     this.applyWidgets(live, filtered, mode, {
    1628              :       documentWidgets: widgets as DocNode['widgets']
    1629              :     })
    1630              :   }
    1631              : 
    1632              :   private propagateInteriorToHost(
    1633              :     host: LGraphNode,
    1634              :     liveInterior: LGraphNode,
    1635              :     record: Record<string, unknown>,
    1636              :     names: ReadonlySet<string>,
    1637              :     mode: ApplyMode
    1638              :   ): void {
    1639            0 :     for (const input of promotedInputs(host)) {
    1640            0 :       const target = host.isSubgraphNode()
    1641              :         ? host.resolvePromotedTarget(input.name)
    1642              :         : undefined
    1643            0 :       if (!target || target.nodeId !== liveInterior.id) continue
    1644            0 :       if (!names.has(target.widgetName)) continue
    1645            0 :       if (!Object.hasOwn(record, target.widgetName)) continue
    1646            0 :       this.applyHostWidgets(
    1647              :         host,
    1648              :         { [input.name]: record[target.widgetName] },
    1649              :         mode
    1650              :       )
    1651              :     }
    1652              :   }
    1653              : 
    1654              :   /**
    1655              :    * `options.documentWidgets` is the node's whole document map. It differs
    1656              :    * from `widgets` on partial frames, where alias precedence still depends on
    1657              :    * every key. Creation can suppress reports for unmatched names while still
    1658              :    * reporting unresolved overflow aliases.
    1659              :    */
    1660              :   private applyWidgets(
    1661              :     node: LGraphNode,
    1662              :     widgets: DocNode['widgets'],
    1663              :     mode: ApplyMode,
    1664              :     options: ApplyWidgetOptions = {}
    1665              :   ): void {
    1666            0 :     if (widgets === undefined) return
    1667            0 :     if (node.isSubgraphNode()) {
    1668            0 :       this.applyHostWidgets(node, widgets, mode)
    1669            0 :       return
    1670              :     }
    1671            0 :     if (Array.isArray(widgets)) {
    1672            0 :       this.applyPositionalWidgets(node, widgets)
    1673            0 :       this.unappliedRegrownRows.delete(node)
    1674            0 :       return
    1675              :     }
    1676            0 :     const { documentWidgets = widgets, reportMissing = true } = options
    1677            0 :     let pending = ordinaryWidgetEntries(node, widgets).filter(isWidgetEntry)
    1678            0 :     while (pending.length > 0) {
    1679            0 :       const { resolved, unresolved } = this.applyWidgetRound(
    1680              :         node,
    1681              :         pending,
    1682              :         documentWidgets
    1683              :       )
    1684            0 :       if (!resolved) {
    1685            0 :         this.reportMissingWidgets(node, unresolved, reportMissing)
    1686            0 :         break
    1687              :       }
    1688            0 :       pending = unresolved
    1689              :     }
    1690            0 :     if (!Array.isArray(documentWidgets))
    1691            0 :       this.checkNestedRowCounts(node, widgets, documentWidgets)
    1692            0 :     this.unappliedRegrownRows.delete(node)
    1693              :   }
    1694              : 
    1695              :   private checkNestedRowCounts(
    1696              :     node: LGraphNode,
    1697              :     widgets: Record<string, unknown>,
    1698              :     documentWidgets: Record<string, unknown>
    1699              :   ): void {
    1700            0 :     const applied = Object.entries(widgets)
    1701              :       .filter(([name, value]) =>
    1702              :         Object.is(documentWidget(node, name)?.value, value)
    1703              :       )
    1704              :       .map(([name]) => name)
    1705            0 :     for (const controller of nestedGroupControllers(
    1706              :       node,
    1707              :       Object.keys(widgets),
    1708              :       applied
    1709              :     )) {
    1710            0 :       const count = documentWidgets[controller.name]
    1711            0 :       if (count === undefined || reachesDynamicGroupRowCount(controller, count))
    1712            0 :         continue
    1713            0 :       reportRemoteDynamicGroupRowMismatch(
    1714              :         node,
    1715              :         count,
    1716              :         Number(controller.value),
    1717              :         { ...AGENT_APPLY_TAGS, outcome: 'degraded' },
    1718              :         'remote_remount'
    1719              :       )
    1720              :     }
    1721              :   }
    1722              : 
    1723              :   private applyPositionalWidgets(node: LGraphNode, widgets: unknown[]): void {
    1724            0 :     let live = serializableWidgets(node)
    1725            0 :     for (
    1726              :       let index = 0;
    1727              :       index < Math.min(widgets.length, live.length);
    1728              :       index++
    1729              :     ) {
    1730            0 :       const widget = live[index]
    1731            0 :       const entry: [string, unknown] = [widget.name, widgets[index]]
    1732            0 :       if (!isWidgetEntry(entry)) continue
    1733            0 :       this.applyWidgetRound(node, [entry], widgets)
    1734            0 :       if (!isDynamicGroupController(widget)) continue
    1735            0 :       if (!reachesDynamicGroupRowCount(widget, entry[1])) return
    1736            0 :       live = serializableWidgets(node)
    1737              :     }
    1738              :   }
    1739              : 
    1740              :   private applyWidgetRound(
    1741              :     node: LGraphNode,
    1742              :     pending: readonly [string, WidgetValue][],
    1743              :     documentWidgets: DocNode['widgets']
    1744              :   ): { resolved: boolean; unresolved: [string, WidgetValue][] } {
    1745            0 :     const unresolved: [string, WidgetValue][] = []
    1746            0 :     let resolved = false
    1747            0 :     for (const [name, value] of pending) {
    1748            0 :       if (supersededOverflowAlias(node, name, documentWidgets)) continue
    1749            0 :       if (this.holdsLocalWrite(node, name, value)) continue
    1750            0 :       const widget = documentWidget(node, name)
    1751            0 :       if (widget === undefined) {
    1752            0 :         unresolved.push([name, value])
    1753            0 :         continue
    1754              :       }
    1755            0 :       if (
    1756              :         widget.name !== name &&
    1757              :         this.holdsLocalWrite(node, widget.name, value)
    1758              :       )
    1759            0 :         continue
    1760            0 :       if (isDynamicGroupController(widget))
    1761            0 :         this.applyDynamicGroupRowCount(node, widget, value)
    1762            0 :       else this.setWidgetValue(node, widget, value)
    1763            0 :       resolved = true
    1764              :     }
    1765            0 :     return { resolved, unresolved }
    1766              :   }
    1767              : 
    1768              :   private reportMissingWidgets(
    1769              :     node: LGraphNode,
    1770              :     unresolved: readonly [string, WidgetValue][],
    1771              :     reportMissing: boolean
    1772              :   ): void {
    1773            0 :     for (const [name] of unresolved) {
    1774            0 :       if (hiddenRowController(node, name)) continue
    1775            0 :       if (selectionDependentAbsence(node, name)) continue
    1776            0 :       if (reportMissing || overflowWidgetIndex(name) !== null)
    1777            0 :         this.reportMissingWidget(node, name)
    1778              :     }
    1779              :   }
    1780              : 
    1781              :   private reportMissingWidget(node: LGraphNode, name: string): void {
    1782            0 :     const overflowIndex = overflowWidgetIndex(name)
    1783            0 :     this.reportOnce(
    1784              :       `widget:${String(node.id)}:${name}`,
    1785              :       `Node ${String(node.id)} (${node.type}) has no widget '${name}'`,
    1786              :       'agent_graph_widget_missing',
    1787              :       {
    1788              :         nodeId: node.id,
    1789              :         type: node.type,
    1790              :         name,
    1791              :         availableWidgetNames: diagnosticWidgetNames(node.widgets ?? []),
    1792              :         ...(overflowIndex === null
    1793              :           ? {}
    1794              :           : {
    1795              :               overflowIndex,
    1796              :               supportsDynamicWidgetOverflow:
    1797              :                 supportsDynamicWidgetOverflow(node),
    1798              :               serializableWidgetNames: diagnosticWidgetNames(
    1799              :                 serializableWidgets(node)
    1800              :               )
    1801              :             })
    1802              :       }
    1803              :     )
    1804              :   }
    1805              : 
    1806              :   private applyConfiguredHostWidgets(
    1807              :     node: LGraphNode,
    1808              :     widgets: DocNode['widgets'],
    1809              :     beforeConfigurePromotedIds: readonly string[],
    1810              :     mode: ApplyMode
    1811              :   ): void {
    1812            0 :     const afterConfigurePromotedIds = promotedWidgetIds(node)
    1813            0 :     if (
    1814              :       Array.isArray(widgets) &&
    1815              :       (widgets.length !== afterConfigurePromotedIds.length ||
    1816              :         !isEqual(beforeConfigurePromotedIds, afterConfigurePromotedIds))
    1817              :     ) {
    1818            0 :       this.reportHostWidgetDrift(
    1819              :         node,
    1820              :         widgets.length,
    1821              :         afterConfigurePromotedIds.length,
    1822              :         mode,
    1823              :         { beforeConfigurePromotedIds, afterConfigurePromotedIds }
    1824              :       )
    1825            0 :       return
    1826              :     }
    1827            0 :     this.applyHostWidgets(node, widgets, mode)
    1828              :   }
    1829              : 
    1830              :   private reportHostWidgetDrift(
    1831              :     node: LGraphNode,
    1832              :     actual: number,
    1833              :     expected: number,
    1834              :     mode: ApplyMode,
    1835              :     identity?: {
    1836              :       beforeConfigurePromotedIds: readonly string[]
    1837              :       afterConfigurePromotedIds: readonly string[]
    1838              :     }
    1839              :   ): void {
    1840            0 :     this.reportOnce(
    1841              :       `host-widgets:${mode}:${String(node.id)}`,
    1842              :       `Subgraph host ${String(node.id)} (${node.type}) carries ${actual} opaque widget values for ${expected} promoted widgets`,
    1843              :       'agent_graph_host_widgets_mismatch',
    1844              :       { nodeId: node.id, type: node.type, expected, actual, mode, ...identity }
    1845              :     )
    1846              :   }
    1847              : 
    1848              :   private applyHostWidgets(
    1849              :     node: LGraphNode,
    1850              :     widgets: DocNode['widgets'],
    1851              :     mode: ApplyMode
    1852              :   ): void {
    1853            0 :     const promoted = promotedInputs(node)
    1854            0 :     if (Array.isArray(widgets) && widgets.length !== promoted.length) {
    1855            0 :       this.reportHostWidgetDrift(node, widgets.length, promoted.length, mode)
    1856            0 :       return
    1857              :     }
    1858            0 :     for (const [name, value] of hostWidgetEntries(promoted, widgets)) {
    1859            0 :       if (!isWidgetValue(value)) continue
    1860            0 :       if (this.holdsLocalWrite(node, name, value)) continue
    1861            0 :       const input = promoted.find((candidate) => candidate.name === name)
    1862            0 :       if (!input) {
    1863            0 :         this.reportOnce(
    1864              :           `widget:${String(node.id)}:${name}`,
    1865              :           `Subgraph host ${String(node.id)} (${node.type}) promotes no widget '${name}'`,
    1866              :           'agent_graph_widget_missing',
    1867              :           { nodeId: node.id, type: node.type, name }
    1868              :         )
    1869            0 :         continue
    1870              :       }
    1871            0 :       const widget = node.getWidgetFromSlot(input)
    1872            0 :       if (!widget) {
    1873            0 :         this.reportOnce(
    1874              :           `widget:${String(node.id)}:${name}:unresolved`,
    1875              :           `Subgraph host ${String(node.id)} (${node.type}) could not resolve promoted widget '${name}'`,
    1876              :           'agent_graph_widget_missing',
    1877              :           { nodeId: node.id, type: node.type, name }
    1878              :         )
    1879            0 :         continue
    1880              :       }
    1881            0 :       try {
    1882            0 :         this.setPromotedWidgetValue(node, widget, value)
    1883              :       } catch (error) {
    1884            0 :         const options = {
    1885              :           surface: 'agent',
    1886              :           errorType: 'agent_graph_apply_failed',
    1887              :           tags: { ...AGENT_APPLY_TAGS, outcome: 'degraded' },
    1888              :           context: {
    1889              :             nodeId: String(node.id),
    1890              :             widget: name
    1891              :           }
    1892              :         } as const
    1893            0 :         reportError(error, options)
    1894              :       }
    1895              :     }
    1896              :   }
    1897              : 
    1898              :   private holdsLocalWrite(
    1899              :     node: LGraphNode,
    1900              :     widget: string,
    1901              :     docValue: WidgetValue
    1902              :   ): boolean {
    1903            0 :     return (
    1904              :       this.deps.holdsLocalWrite?.(String(node.id), widget, docValue) ?? false
    1905              :     )
    1906              :   }
    1907              : 
    1908              :   private applyDynamicGroupRowCount(
    1909              :     node: LGraphNode,
    1910              :     widget: IBaseWidget,
    1911              :     value: WidgetValue
    1912              :   ) {
    1913            0 :     const requested =
    1914              :       typeof value === 'number' && Number.isFinite(value)
    1915              :         ? Math.max(widget.options.min ?? 0, Math.trunc(value))
    1916              :         : null
    1917            0 :     if (
    1918              :       requested !== null &&
    1919              :       requested > dynamicGroupRowAllocationBound(widget)
    1920              :     ) {
    1921            0 :       this.reportDynamicGroupRowMismatch(node, widget, value)
    1922            0 :       return
    1923              :     }
    1924              :     const applied = applyRemoteDynamicGroupRowCount(node, () =>
    1925              :       this.assignWidgetValue(node, widget, value)
    1926              :     )
    1927            0 :     if (applied && reachesDynamicGroupRowCount(widget, value)) return
    1928            0 :     this.reportDynamicGroupRowMismatch(node, widget, value)
    1929              :   }
    1930              : 
    1931              :   private reportDynamicGroupRowMismatch(
    1932              :     node: LGraphNode,
    1933              :     widget: IBaseWidget,
    1934              :     value: WidgetValue
    1935              :   ) {
    1936            0 :     this.incrementFailureCount()
    1937            0 :     reportRemoteDynamicGroupRowMismatch(node, value, Number(widget.value), {
    1938              :       ...AGENT_APPLY_TAGS,
    1939              :       outcome: 'degraded'
    1940              :     })
    1941              :   }
    1942              : 
    1943              :   private setWidgetValue(
    1944              :     node: LGraphNode,
    1945              :     widget: IBaseWidget,
    1946              :     value: WidgetValue
    1947              :   ) {
    1948            0 :     if (widget.type === 'button' || Object.is(widget.value, value)) return
    1949            0 :     if (!(widget instanceof BaseWidget)) {
    1950            0 :       this.assignWidgetValue(node, widget, value)
    1951            0 :       return
    1952              :     }
    1953            0 :     const rollback = captureWidgetValue(node, widget)
    1954            0 :     try {
    1955            0 :       widget.setValue(value, {
    1956              :         node,
    1957              :         canvas: this.deps.getCanvas?.() ?? undefined
    1958              :       })
    1959              :     } catch (error) {
    1960            0 :       rollback()
    1961            0 :       throw error
    1962              :     }
    1963              :   }
    1964              : 
    1965              :   private assignWidgetValue(
    1966              :     node: LGraphNode,
    1967              :     widget: IBaseWidget,
    1968              :     value: WidgetValue
    1969              :   ): boolean {
    1970            0 :     if (widget.type === 'button') return false
    1971            0 :     if (Object.is(widget.value, value)) return true
    1972            0 :     const previous = widget.value
    1973            0 :     const rollback = writeWidgetValue(node, widget, value)
    1974            0 :     if (!widgetAcceptedValue(widget, value)) {
    1975            0 :       rollback()
    1976            0 :       return false
    1977              :     }
    1978            0 :     try {
    1979            0 :       widget.callback?.(value, this.deps.getCanvas?.() ?? undefined, node)
    1980            0 :       node.onWidgetChanged?.(widget.name, value, previous, widget)
    1981              :     } catch (error) {
    1982            0 :       rollback()
    1983            0 :       throw error
    1984              :     }
    1985            0 :     node.graph?.incrementVersion()
    1986            0 :     return true
    1987              :   }
    1988              : 
    1989              :   private setPromotedWidgetValue(
    1990              :     node: LGraphNode,
    1991              :     widget: IBaseWidget,
    1992              :     value: WidgetValue
    1993              :   ): void {
    1994            0 :     if (widget.type === 'button' || Object.is(widget.value, value)) return
    1995            0 :     const previous = widget.value
    1996            0 :     const callback = widget.callback
    1997            0 :     function writeWithoutCallback<T>(write: () => T): T {
    1998            0 :       widget.callback = undefined
    1999            0 :       try {
    2000            0 :         return write()
    2001              :       } finally {
    2002            0 :         widget.callback = callback
    2003              :       }
    2004              :     }
    2005            0 :     const rollback = writeWithoutCallback(() =>
    2006              :       writeWidgetValue(node, widget, value, false)
    2007              :     )
    2008            0 :     try {
    2009            0 :       callback?.call(widget, value, this.deps.getCanvas?.() ?? undefined, node)
    2010            0 :       node.onWidgetChanged?.(widget.name, value, previous, widget)
    2011            0 :       if (!Object.is(widget.value, value)) {
    2012            0 :         writeWithoutCallback(() => writeWidgetValue(node, widget, value, false))
    2013              :       }
    2014              :     } catch (error) {
    2015            0 :       writeWithoutCallback(rollback)
    2016            0 :       throw error
    2017              :     }
    2018            0 :     node.graph?.incrementVersion()
    2019              :   }
    2020              : 
    2021              :   private applyLinks(
    2022              :     graph: LGraph,
    2023              :     doc: Y.Doc,
    2024              :     keys: readonly string[],
    2025              :     context: RemoteApplyContext
    2026              :   ): void {
    2027            0 :     const retry: DocLink[] = []
    2028            0 :     for (const key of keys) {
    2029            0 :       const link = readDocLink(doc, key)
    2030            0 :       if (!link) {
    2031            0 :         const id = parseLinkId(key)
    2032            0 :         if (id !== undefined)
    2033            0 :           this.try(context, () => graph.removeLink(toLinkId(id)))
    2034            0 :         continue
    2035              :       }
    2036            0 :       this.try(context, () => {
    2037            0 :         if (this.connectLink(graph, doc, link) === 'unresolved')
    2038            0 :           retry.push(link)
    2039              :       })
    2040              :     }
    2041            0 :     for (const link of retry) {
    2042            0 :       this.try(context, () => {
    2043            0 :         if (this.connectLink(graph, doc, link) !== 'connected') {
    2044            0 :           this.reportOnce(
    2045              :             `link:${link.id}`,
    2046              :             `Link ${link.id} (node ${link.origin} slot ${link.originSlot} -> node ${link.target} slot ${link.targetSlot}) could not be connected on the live graph`,
    2047              :             'agent_graph_link_unresolved',
    2048              :             { ...link }
    2049              :           )
    2050              :         }
    2051              :       })
    2052              :     }
    2053              :   }
    2054              : 
    2055              :   private connectLink(
    2056              :     graph: LGraph,
    2057              :     doc: Y.Doc,
    2058              :     link: DocLink
    2059              :   ): 'connected' | 'present' | 'unresolved' | 'refused' | 'missing-node' {
    2060            0 :     const origin = graph.getNodeById(toNodeId(link.origin))
    2061            0 :     const target = graph.getNodeById(toNodeId(link.target))
    2062            0 :     if (!origin || !target) return 'missing-node'
    2063              : 
    2064            0 :     const originSlot = resolveSlot(
    2065              :       origin.outputs.map((output) => output.name),
    2066              :       readDocSlotName(doc, link.origin, 'outputs', link.originSlot),
    2067              :       link.originSlot,
    2068              :       'positional'
    2069              :     )
    2070            0 :     const targetSlot = resolveTargetSlot(target, doc, link)
    2071            0 :     if (originSlot < 0 || targetSlot < 0) {
    2072            0 :       if (graph.links.has(link.id)) graph.removeLink(link.id)
    2073            0 :       return 'unresolved'
    2074              :     }
    2075            0 :     if (isLinkPresent(graph, origin, originSlot, target, targetSlot))
    2076            0 :       return 'present'
    2077            0 :     if (graph.links.has(link.id)) graph.removeLink(link.id)
    2078              : 
    2079              :     const created = withLinkId(graph, link.id, () =>
    2080              :       origin.connect(originSlot, target, targetSlot)
    2081              :     )
    2082            0 :     return created ? 'connected' : 'refused'
    2083              :   }
    2084              : 
    2085              :   private placeBatch(
    2086              :     graph: LGraph,
    2087              :     created: readonly NodeId[],
    2088              :     createdGroups: readonly LGraphGroup[],
    2089              :     { moveCollisions }: { moveCollisions: boolean }
    2090              :   ): void {
    2091            0 :     const createdSet = new Set(created)
    2092            0 :     const rect = (item: LGraphNode | LGraphGroup): PlacementRect => ({
    2093              :       x: item.pos[0],
    2094              :       y: item.pos[1],
    2095              :       width: item.size[0],
    2096              :       height: item.size[1]
    2097              :     })
    2098            0 :     const createdNodes = graph._nodes.filter((node) => createdSet.has(node.id))
    2099            0 :     const existingNodes = graph._nodes.filter(
    2100              :       (node) => !createdSet.has(node.id)
    2101              :     )
    2102            0 :     const ctx = this.deps.getCanvas?.()?.ctx ?? undefined
    2103            0 :     const existingBounds = existingNodes.map((node) =>
    2104              :       isRendered(node) ? node.boundingRect : pendingBounds(node, ctx)
    2105              :     )
    2106            0 :     const createdBounds = createdNodes.map((node) => pendingBounds(node, ctx))
    2107            0 :     const framesOnlyExisting = (group: LGraphGroup) =>
    2108              :       framesAny(group, existingBounds) && !framesAny(group, createdBounds)
    2109            0 :     const kept = createdGroups.filter(framesOnlyExisting)
    2110            0 :     const placedGroups =
    2111              :       kept.length > 0 && createdNodes.length === 0
    2112              :         ? []
    2113              :         : createdGroups.filter((group) => !kept.includes(group))
    2114            0 :     const incoming = [...createdNodes, ...placedGroups]
    2115            0 :     const offset = placementOffset({
    2116              :       existing: [
    2117              :         ...existingNodes,
    2118              :         ...graph.groups.filter((group) => !placedGroups.includes(group))
    2119              :       ].map(rect),
    2120              :       viewport: this.deps.viewportBounds?.() ?? null,
    2121              :       incoming: incoming.map(rect),
    2122              :       moveCollisions
    2123              :     })
    2124            0 :     if (!offset) return
    2125            0 :     for (const item of incoming) {
    2126            0 :       item.pos = [item.pos[0] + offset.dx, item.pos[1] + offset.dy]
    2127              :     }
    2128              :   }
    2129              : }
    2130              : 
    2131              : /** True once a frame has measured the node; until then its bounds are zero. */
    2132            0 : function isRendered(node: LGraphNode): boolean {
    2133            0 :   const [, , width, height] = node.boundingRect
    2134            0 :   return width > 0 || height > 0
    2135              : }
    2136              : 
    2137              : /**
    2138              :  * The bounds the next frame will give a node that has not been drawn yet,
    2139              :  * measured the way LiteGraph does it, including a collapsed node's title width.
    2140              :  * `measure()` caches the collapsed width the node renders at; that cache is
    2141              :  * left for the next frame to write, because without a canvas context it would
    2142              :  * be written as zero.
    2143              :  */
    2144            0 : function pendingBounds(
    2145              :   node: LGraphNode,
    2146              :   ctx: CanvasRenderingContext2D | undefined
    2147              : ): ReadOnlyRect {
    2148            0 :   const out: Rect = [0, 0, 0, 0]
    2149            0 :   const collapsedWidth = node._collapsed_width
    2150            0 :   node.measure(out, ctx)
    2151            0 :   node._collapsed_width = collapsedWidth
    2152            0 :   return out
    2153              : }
    2154              : 
    2155            0 : function framesAny(
    2156              :   group: LGraphGroup,
    2157              :   bounds: readonly ReadOnlyRect[]
    2158              : ): boolean {
    2159            0 :   return bounds.some((rect) => containsCentre(group._bounding, rect))
    2160              : }
    2161              : 
    2162            0 : function isLinkPresent(
    2163              :   graph: LGraph,
    2164              :   origin: LGraphNode,
    2165              :   originSlot: number,
    2166              :   target: LGraphNode,
    2167              :   targetSlot: number
    2168              : ): boolean {
    2169            0 :   const currentId = target.inputs[targetSlot]?.link
    2170            0 :   const current = currentId == null ? undefined : graph.links.get(currentId)
    2171            0 :   return (
    2172              :     current !== undefined &&
    2173              :     current.origin_id === origin.id &&
    2174              :     current.origin_slot === originSlot
    2175              :   )
    2176              : }
    2177              : 
    2178              : /** Rank of a not-yet-mounted document name; past every live/overflow position. */
    2179            1 : const MOUNTED_LAST = Number.MAX_SAFE_INTEGER
    2180              : 
    2181              : /**
    2182              :  * Apply order for a document widget map: live widgets in their positional
    2183              :  * order, then overflow aliases by position, then names no widget carries yet.
    2184              :  * The live order keeps a selector ahead of children it may rebuild. Unresolved
    2185              :  * entries are retried after each round, so selectors can mount widgets at any
    2186              :  * depth.
    2187              :  */
    2188            0 : function widgetEntryRank(node: LGraphNode, name: string): number {
    2189            0 :   const live = serializableWidgets(node)
    2190            0 :   const liveIndex = live.findIndex((widget) => widget.name === name)
    2191            0 :   if (liveIndex !== -1) return liveIndex
    2192            0 :   const index = overflowWidgetIndex(name)
    2193            0 :   return index === null ? MOUNTED_LAST : live.length + index
    2194              : }
    2195              : 
    2196            0 : function nestedGroupControllers(
    2197              :   node: LGraphNode,
    2198              :   written: readonly string[],
    2199              :   applied: readonly string[]
    2200              : ): IBaseWidget[] {
    2201            0 :   const under = (name: string, parent: string) => name.startsWith(`${parent}.`)
    2202            0 :   return (node.widgets ?? []).filter(
    2203              :     (widget) =>
    2204              :       isDynamicGroupController(widget) &&
    2205              :       !written.includes(widget.name) &&
    2206              :       applied.some((name) => under(widget.name, name)) &&
    2207              :       !written.some(
    2208              :         (name) => !applied.includes(name) && under(widget.name, name)
    2209              :       )
    2210              :   )
    2211              : }
    2212              : 
    2213            0 : function isWidgetEntry(
    2214              :   entry: [string, unknown]
    2215              : ): entry is [string, WidgetValue] {
    2216            0 :   return entry[1] !== undefined && isWidgetValue(entry[1])
    2217              : }
    2218              : 
    2219            0 : function ordinaryWidgetEntries(
    2220              :   node: LGraphNode,
    2221              :   widgets: Record<string, unknown>
    2222              : ): [string, unknown][] {
    2223            0 :   return Object.entries(widgets).sort(
    2224              :     ([a], [b]) => widgetEntryRank(node, a) - widgetEntryRank(node, b)
    2225              :   )
    2226              : }
    2227              : 
    2228            0 : function restoreWidgetRecord(
    2229              :   node: LGraphNode,
    2230              :   record: Record<string, unknown>
    2231              : ): void {
    2232            0 :   const widgets_values = record as unknown as WidgetValue[]
    2233            0 :   if (node.has_errors) {
    2234            0 :     const snapshot = node.last_serialization
    2235            0 :     if (snapshot) node.last_serialization = { ...snapshot, widgets_values }
    2236            0 :     return
    2237              :   }
    2238            0 :   configureRemoteNode(node, {
    2239              :     ...omit(node.serialize(), ['widgets_values_named']),
    2240              :     widgets_values
    2241              :   })
    2242              : }
    2243              : 
    2244              : /**
    2245              :  * Whether the changed-name set covers this document key, either directly or
    2246              :  * through the live widget an overflow alias resolves to (rejected-op name sets
    2247              :  * carry the widget's real name).
    2248              :  */
    2249            0 : function changed(
    2250              :   node: LGraphNode,
    2251              :   name: string,
    2252              :   names: ReadonlySet<string>
    2253              : ): boolean {
    2254            0 :   if (names.has(name)) return true
    2255            0 :   const positional = overflowWidget(node, name)
    2256            0 :   return positional !== undefined && names.has(positional.name)
    2257              : }
    2258              : 
    2259              : type InteriorSyncTargets = Map<string, Map<string, ReadonlySet<string> | 'all'>>
    2260              : 
    2261            0 : function interiorSyncTargets(
    2262              :   granular: InteriorChanges | undefined,
    2263              :   full: ReadonlySet<string> | undefined,
    2264              :   docInteriors: ReturnType<typeof readSubgraphInteriorWidgets>
    2265              : ): InteriorSyncTargets {
    2266            0 :   const targets: InteriorSyncTargets = new Map()
    2267            0 :   if (granular) {
    2268            0 :     for (const [definitionId, nodes] of granular) {
    2269            0 :       targets.set(definitionId, new Map(nodes))
    2270              :     }
    2271              :   }
    2272            0 :   if (full) {
    2273            0 :     for (const definitionId of full) {
    2274            0 :       const nodes = targets.get(definitionId) ?? new Map()
    2275            0 :       for (const nodeId of docInteriors.get(definitionId)?.keys() ?? []) {
    2276            0 :         if (!nodes.has(nodeId)) nodes.set(nodeId, 'all')
    2277              :       }
    2278            0 :       targets.set(definitionId, nodes)
    2279              :     }
    2280              :   }
    2281            0 :   return targets
    2282              : }
    2283              : 
    2284            0 : function promotedInputs(node: LGraphNode): INodeInputSlot[] {
    2285            0 :   return node.inputs.filter((input) => input.widgetId)
    2286              : }
    2287              : 
    2288            0 : function subgraphHostInstances(
    2289              :   graph: LGraph,
    2290              :   definitionId: string
    2291              : ): LGraphNode[] {
    2292            0 :   const hosts: LGraphNode[] = []
    2293            0 :   const seen = new Set<LGraphNode>()
    2294            0 :   const visit = (nodes: readonly LGraphNode[]): void => {
    2295            0 :     for (const node of nodes) {
    2296            0 :       if (seen.has(node)) continue
    2297            0 :       seen.add(node)
    2298            0 :       if (node.isSubgraphNode() && node.subgraph.id === definitionId) {
    2299            0 :         hosts.push(node)
    2300              :       }
    2301              :     }
    2302              :   }
    2303            0 :   visit(graph.rootGraph.nodes)
    2304            0 :   for (const subgraph of graph.rootGraph.subgraphs.values())
    2305            0 :     visit(subgraph.nodes)
    2306            0 :   return hosts
    2307              : }
    2308              : 
    2309            0 : function promotedWidgetIds(node: LGraphNode): string[] {
    2310            0 :   return promotedInputs(node).flatMap((input) =>
    2311              :     input.widgetId ? [input.widgetId] : []
    2312              :   )
    2313              : }
    2314              : 
    2315              : /** Host widget values by promoted-input name; a positional list is read in promoted-input order. */
    2316            0 : function hostWidgetEntries(
    2317              :   promoted: readonly INodeInputSlot[],
    2318              :   widgets: DocNode['widgets']
    2319              : ): [string, unknown][] {
    2320            0 :   if (Array.isArray(widgets))
    2321            0 :     return promoted.map((input, index) => [input.name, widgets[index]])
    2322            0 :   return Object.entries(widgets ?? {})
    2323              : }
    2324              : 
    2325            0 : function captureWidgetValue(
    2326              :   node: LGraphNode,
    2327              :   widget: IBaseWidget,
    2328              :   mirrorProperty = true
    2329              : ): () => void {
    2330            0 :   const previous = widget.value
    2331            0 :   const property = widget.options.property
    2332            0 :   if (!mirrorProperty || !property || node.properties[property] === undefined)
    2333            0 :     return () => {
    2334            0 :       widget.value = previous
    2335              :     }
    2336            0 :   const previousProperty = node.properties[property]
    2337            0 :   return () => {
    2338            0 :     widget.value = previous
    2339            0 :     node.setProperty(property, previousProperty)
    2340              :   }
    2341              : }
    2342              : 
    2343            0 : function writeWidgetValue(
    2344              :   node: LGraphNode,
    2345              :   widget: IBaseWidget,
    2346              :   value: WidgetValue,
    2347              :   mirrorProperty = true
    2348              : ): () => void {
    2349            0 :   const rollback = captureWidgetValue(node, widget, mirrorProperty)
    2350            0 :   const property = widget.options.property
    2351            0 :   widget.value = value
    2352            0 :   if (mirrorProperty && property && node.properties[property] !== undefined)
    2353            0 :     node.setProperty(property, value)
    2354            0 :   return rollback
    2355              : }
    2356              : 
    2357            0 : function applyFlags(
    2358              :   node: LGraphNode,
    2359              :   flags: INodeFlags,
    2360              :   keys?: ReadonlySet<string>
    2361              : ): void {
    2362            0 :   const edited = (key: string) =>
    2363              :     !keys || keys.has('flags') || keys.has(`flags.${key}`)
    2364            0 :   if (edited('collapsed') && node.collapsed !== !!flags.collapsed)
    2365            0 :     node.collapse(true)
    2366            0 :   if (edited('pinned') && node.pinned !== !!flags.pinned)
    2367            0 :     node.pin(!!flags.pinned)
    2368            0 :   for (const [key, value] of Object.entries({ ...node.flags, ...flags })) {
    2369            0 :     if (['ghost', 'collapsed', 'pinned'].includes(key) || !edited(key)) continue
    2370            0 :     if (key in flags) {
    2371            0 :       Object.assign(node.flags, { [key]: value })
    2372              :     } else {
    2373            0 :       Reflect.deleteProperty(node.flags, key)
    2374              :     }
    2375              :   }
    2376              : }
    2377              : 
    2378            0 : function applyProperties(
    2379              :   node: LGraphNode,
    2380              :   properties: ISerialisedNode['properties']
    2381              : ): void {
    2382            0 :   for (const [key, value] of Object.entries(properties ?? {})) {
    2383            0 :     if (node.properties[key] !== value) node.setProperty(key, value)
    2384              :   }
    2385              : }
    2386              : 
    2387            0 : function applyAppearance(
    2388              :   node: LGraphNode,
    2389              :   source: ISerialisedNode,
    2390              :   edited: (key: string) => boolean
    2391              : ): void {
    2392            0 :   const target = (key: 'color' | 'bgcolor') =>
    2393              :     edited(key) ? (source[key] ?? node[key]) : node[key]
    2394            0 :   const color = target('color')
    2395            0 :   const bgcolor = target('bgcolor')
    2396            0 :   if (node.color !== color || node.bgcolor !== bgcolor) {
    2397            0 :     const option = Object.values(LGraphCanvas.node_colors).find(
    2398              :       (option) => option.color === color && option.bgcolor === bgcolor
    2399              :     )
    2400            0 :     if (option) node.setColorOption(option)
    2401              :   }
    2402            0 :   for (const key of SYNCED_APPEARANCE_FIELDS.filter(edited)) {
    2403            0 :     const value = source[key]
    2404            0 :     if (value !== undefined && node[key] !== value) {
    2405            0 :       Object.assign(node, { [key]: value })
    2406              :     }
    2407              :   }
    2408              : }
    2409              : 
    2410              : /**
    2411              :  * The live input index a document link targets. A dynamic input slot the host
    2412              :  * grew has no live counterpart until the node's autogrow group is grown to it,
    2413              :  * so grow it rather than drop a link the document holds against a slot it
    2414              :  * legitimately owns. `growAutogrowInput` refuses a name outside the node's own
    2415              :  * groups, leaving a slot the live node really lacks unresolved as before.
    2416              :  */
    2417            0 : function resolveTargetSlot(
    2418              :   target: LGraphNode,
    2419              :   doc: Y.Doc,
    2420              :   link: DocLink
    2421              : ): number {
    2422            0 :   const docName = readDocSlotName(doc, link.target, 'inputs', link.targetSlot)
    2423            0 :   const resolved = resolveSlot(
    2424              :     target.inputs.map((input) => input.name),
    2425              :     docName,
    2426              :     link.targetSlot,
    2427              :     'none'
    2428              :   )
    2429            0 :   if (resolved >= 0 || docName === undefined) return resolved
    2430            0 :   return growAutogrowInput(target, docName) ?? resolved
    2431              : }
    2432              : 
    2433              : /**
    2434              :  * Resolves a document slot to a live slot index, by name first. `ComfyNode.configure`
    2435              :  * keeps every document input name live (definition or extra), so an input
    2436              :  * name the live node lacks is a real mismatch and never a positional guess.
    2437              :  * It matches outputs by index and lets the definition's names win over the
    2438              :  * document's, so an output resolves by position when its document name is
    2439              :  * stale.
    2440              :  */
    2441            0 : function resolveSlot(
    2442              :   liveNames: readonly string[],
    2443              :   docName: string | undefined,
    2444              :   docIndex: number,
    2445              :   fallback: 'positional' | 'none'
    2446              : ): number {
    2447            0 :   const byName = docName === undefined ? -1 : liveNames.indexOf(docName)
    2448            0 :   if (byName >= 0 || (docName !== undefined && fallback === 'none')) {
    2449            0 :     return byName
    2450              :   }
    2451            0 :   return docIndex < liveNames.length ? docIndex : -1
    2452              : }
    2453              : 
    2454              : /**
    2455              :  * Root ids the document owns. Definitions register before the frame's root
    2456              :  * nodes and links exist live, so id deduplication has to be told about them
    2457              :  * or it hands a definition interior an id the root graph is about to need.
    2458              :  */
    2459            0 : function docRootIds(doc: Y.Doc): { nodeIds: NodeId[]; linkIds: number[] } {
    2460            0 :   const nodeIds: NodeId[] = []
    2461            0 :   nodesMap(doc).forEach((_, id) => nodeIds.push(toNodeId(id)))
    2462            0 :   const linkIds: number[] = []
    2463            0 :   linksMap(doc).forEach((_, key) => {
    2464            0 :     const id = parseLinkId(key)
    2465            0 :     if (id !== undefined) linkIds.push(id)
    2466              :   })
    2467            0 :   return { nodeIds, linkIds }
    2468              : }
    2469              : 
    2470            0 : function tryCreateSubgraph(
    2471              :   rootGraph: LGraph,
    2472              :   definition: ExportedSubgraph,
    2473              :   reserved: { nodeIds: NodeId[]; linkIds: number[] }
    2474              : ): unknown {
    2475            0 :   if (!isUuidShapedSubgraphId(definition.id)) {
    2476            0 :     return new Error(
    2477              :       `Agent subgraph definition id is not a UUID: ${definition.id}`
    2478              :     )
    2479              :   }
    2480            0 :   try {
    2481            0 :     withNamedValuesRestore(() =>
    2482              :       rootGraph.createSubgraphs([definition], reserved)
    2483              :     )
    2484            0 :     return undefined
    2485              :   } catch (cause) {
    2486            0 :     const halfBuilt = rootGraph.subgraphs.get(definition.id)
    2487            0 :     if (halfBuilt) {
    2488            0 :       try {
    2489            0 :         rootGraph.releaseSubgraphs([halfBuilt])
    2490              :       } catch (rollbackCause) {
    2491            0 :         return new AggregateError(
    2492              :           [cause, rollbackCause],
    2493              :           `Agent subgraph definition ${definition.id} failed to register and roll back`
    2494              :         )
    2495              :       }
    2496              :     }
    2497            0 :     return cause
    2498              :   }
    2499              : }
    2500              : 
    2501              : /**
    2502              :  * Definitions carry interior widget values by name
    2503              :  * (`widgets_values_named`); `configure` only reads them while the
    2504              :  * `namedValuesRestore` flag is set, so set it for the definition alone.
    2505              :  */
    2506            0 : function withNamedValuesRestore<T>(fn: () => T): T {
    2507            0 :   const previous = LiteGraph.namedValuesRestore
    2508            0 :   LiteGraph.namedValuesRestore = true
    2509            0 :   try {
    2510            0 :     return fn()
    2511              :   } finally {
    2512            0 :     LiteGraph.namedValuesRestore = previous
    2513              :   }
    2514              : }
        

Generated by: LCOV version 2.0-1