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

            Line data    Source code
       1              : import {
       2              :   computed,
       3              :   effectScope,
       4              :   onScopeDispose,
       5              :   readonly,
       6              :   ref,
       7              :   shallowRef,
       8              :   watch
       9              : } from 'vue'
      10              : import type { Ref } from 'vue'
      11              : 
      12              : import {
      13              :   observedDocCounter,
      14              :   SCHEMA_VERSION,
      15              :   SchemaVersionError
      16              : } from '@comfyorg/comfy-multi-player'
      17              : import type { Op } from '@comfyorg/comfy-multi-player'
      18              : 
      19              : import type { LGraph } from '@/lib/litegraph/src/litegraph'
      20              : import { useTelemetry } from '@comfyorg/telemetry'
      21              : import { reportError } from '@comfyorg/telemetry/reportError'
      22              : import type { AgentGraphProjectionStage } from '@comfyorg/telemetry/types'
      23              : import { parseNodeId } from '@comfyorg/graph-model/nodeId'
      24              : import type { NodeId } from '@comfyorg/graph-model/nodeId'
      25              : import { createUuidv4 } from '@/utils/uuid'
      26              : import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore'
      27              : 
      28              : import type {
      29              :   AgentCrdtOutcomeCounters,
      30              :   AgentCrdtTerminalState,
      31              :   AgentCrdtStatus
      32              : } from './agentCrdtStatus'
      33              : import {
      34              :   AgentCrdtDocLifecycle,
      35              :   STALE_AFTER_MS,
      36              :   SUBSCRIBE_CATCHUP_GRACE_MS
      37              : } from './agentCrdtDocLifecycle'
      38              : import { AgentCrdtProjection } from './agentCrdtProjection'
      39              : import type { DocNodeDelta, FrameOutcome } from './agentCrdtProjection'
      40              : import { createLoggedTransport } from './agentCrdtTransport'
      41              : import type { AgentDocFrameTransport } from './agentDocFrameTransport'
      42              : import { recordDevEvent } from './devPanelLog'
      43              : import type { CrdtDebugSnapshot } from './crdtSnapshot'
      44              : import { readCrdtSnapshot } from './crdtSnapshot'
      45              : import { DocFrameClient } from './docFrameClient'
      46              : import {
      47              :   RESEED_CONFLICT,
      48              :   isPermanentSubscribeRefusalCode,
      49              :   isRetryableReseedCode
      50              : } from './docFrameCodes'
      51              : import type { GraphOperation } from './graphOperations'
      52              : import type { ClassifiedDocUpdate } from './layoutFollowerBridge'
      53              : import { LayoutFollowerBridge, isLiveAgentUpdate } from './layoutFollowerBridge'
      54              : import type { LiveGraphApplierDeps } from './liveGraphApplier'
      55              : import {
      56              :   readDocPromotedWidgets,
      57              :   readSubgraphDefinitionIds
      58              : } from './agentSubgraphDefinitions'
      59              : import { readDocSlotNames, readDocWidgetValue } from './liveGraphApplier'
      60              : import { createOpCoalescer } from './opCoalescer'
      61              : import { createOpSender } from './opSender'
      62              : import type { BatchOutcome, OpsResultView } from './opSender'
      63              : import { createRejectedOpNotifier } from './rejectedOpNotice'
      64              : import type { LostEdits } from './rejectedOpNotice'
      65              : import {
      66              :   forgetUnsyncedAtLoad,
      67              :   recordUnsyncedHumanOps,
      68              :   releaseUnsyncedHumanOpsRecorder
      69              : } from './unsyncedHumanOps'
      70              : 
      71              : export { STALE_AFTER_MS, SUBSCRIBE_CATCHUP_GRACE_MS }
      72              : 
      73              : interface ProjectionFrameId {
      74              :   opIds?: readonly string[]
      75              :   seq: number
      76              :   isLive?: boolean
      77              : }
      78              : 
      79            1 : const NOTHING_APPLIED: FrameOutcome = {
      80              :   applied: false,
      81              :   nodes: { added: [], removed: [] }
      82              : }
      83              : 
      84            0 : function isAgentFrame(actor: string | undefined): boolean {
      85            0 :   return actor === undefined || actor.startsWith('agent:')
      86              : }
      87              : 
      88            0 : function projectionAppliedCleanly(outcome: FrameOutcome): boolean {
      89            0 :   return outcome.applied && outcome.failureCount === 0
      90              : }
      91              : 
      92            0 : function reportAgentProjection(
      93              :   frame: ProjectionFrameId,
      94              :   stage: AgentGraphProjectionStage,
      95              :   outcome: FrameOutcome
      96              : ): void {
      97            0 :   const opIds = frame.opIds?.filter((id) => id.length > 0) ?? []
      98            0 :   useTelemetry()?.trackAgentGraphProjection({
      99              :     op_id: opIds[0] ?? null,
     100              :     op_count: opIds.length,
     101              :     sequence: frame.seq,
     102              :     stage,
     103              :     added_count: outcome.nodes.added.length,
     104              :     removed_count: outcome.nodes.removed.length,
     105              :     apply_failure_count: outcome.applied ? outcome.failureCount : 0
     106              :   })
     107              : }
     108              : 
     109            0 : function liveAddedNodeIds(
     110              :   added: readonly string[],
     111              :   graph: LGraph | null
     112              : ): NodeId[] {
     113            0 :   if (!graph) return []
     114            0 :   return added.flatMap((id) => {
     115            0 :     const nodeId = parseNodeId(id)
     116            0 :     return nodeId && graph.getNodeById(nodeId) ? [nodeId] : []
     117              :   })
     118              : }
     119              : 
     120            0 : function emitPendingMaterializations(
     121              :   workflowId: string,
     122              :   actor: string | undefined,
     123              :   available: ReadonlySet<NodeId>,
     124              :   pending: Set<NodeId>,
     125              :   events: AgentCrdtFollowerEvents
     126              : ): void {
     127            0 :   const nodeIds = [...pending].filter((id) => available.has(id))
     128            0 :   for (const nodeId of nodeIds) pending.delete(nodeId)
     129            0 :   if (nodeIds.length === 0) return
     130            0 :   events.onMaterialized?.({ workflowId, actor, nodeIds })
     131              : }
     132              : 
     133              : interface SubscribeRefusalOutcome {
     134              :   shouldNotify: boolean
     135              :   message?: string
     136              :   code?: string
     137              : }
     138              : 
     139              : // PM-1604 / BE-11437: a subscribe refusal carries a `code` that is either
     140              : // retryable (the lifecycle keeps retrying on its own) or one of
     141              : // `PERMANENT_SUBSCRIBE_REFUSAL_CODES`, which the lifecycle won't recover
     142              : // from by itself — surface those to the person via `onSyncError`, except
     143              : // `unsupported`, which the lifecycle already declines to notify (a
     144              : // deployment with the doc surface off shouldn't toast every user). The
     145              : // caller notifies only after its own held-ops cleanup, matching
     146              : // `onDocReset`'s cleanup-before-notify order, so a throw from consumer code
     147              : // reaching into the toast store can't strand an in-flight op batch. `code`
     148              : // rides along so the presentation layer can pick accurate copy instead of
     149              : // collapsing every permanent code to the same message.
     150            0 : function handleSubscribeRefusal(
     151              :   detail: { code?: unknown; message?: unknown } | null,
     152              :   lifecycle: AgentCrdtDocLifecycle
     153              : ): SubscribeRefusalOutcome {
     154            0 :   const code = typeof detail?.code === 'string' ? detail.code : undefined
     155              :   const shouldNotify = lifecycle.onSubscribeRefused(code)
     156            0 :   return {
     157              :     shouldNotify,
     158              :     message: typeof detail?.message === 'string' ? detail.message : undefined,
     159              :     code
     160              :   }
     161              : }
     162              : 
     163            0 : function notifyAgentMaterialization(
     164              :   update: ClassifiedDocUpdate,
     165              :   nodes: DocNodeDelta,
     166              :   materialized: readonly NodeId[],
     167              :   graph: LGraph | null,
     168              :   pendingLiveNodeIds: Set<NodeId>,
     169              :   events: AgentCrdtFollowerEvents
     170              : ): void {
     171            0 :   for (const id of nodes.removed) {
     172            0 :     const nodeId = parseNodeId(id)
     173            0 :     if (nodeId) pendingLiveNodeIds.delete(nodeId)
     174              :   }
     175            0 :   const liveAgentUpdate = isLiveAgentUpdate(update)
     176            0 :   if (liveAgentUpdate) {
     177            0 :     for (const nodeId of materialized) pendingLiveNodeIds.add(nodeId)
     178            0 :     for (const id of nodes.added) {
     179            0 :       const nodeId = parseNodeId(id)
     180            0 :       if (nodeId) pendingLiveNodeIds.add(nodeId)
     181              :     }
     182              :   }
     183            0 :   const available = new Set([
     184              :     ...materialized,
     185              :     ...liveAddedNodeIds(nodes.added, graph)
     186              :   ])
     187            0 :   emitPendingMaterializations(
     188              :     update.workflowId,
     189              :     liveAgentUpdate ? update.actor : undefined,
     190              :     available,
     191              :     pendingLiveNodeIds,
     192              :     events
     193              :   )
     194              : }
     195              : 
     196            0 : function hasNodes(
     197              :   canvas: Record<string, unknown> | null
     198              : ): canvas is Record<string, unknown> {
     199            0 :   return Array.isArray(canvas?.nodes) && canvas.nodes.length > 0
     200              : }
     201              : 
     202              : type OpsResultDropReason = 'inactive_target' | 'workflow_mismatch'
     203              : 
     204            0 : function opsResultDropReason(
     205              :   active: boolean,
     206              :   workflowId: unknown,
     207              :   subscribedWorkflowId: string | null
     208              : ): OpsResultDropReason | null {
     209            0 :   if (!active) return 'inactive_target'
     210            0 :   return workflowId === subscribedWorkflowId ? null : 'workflow_mismatch'
     211              : }
     212              : 
     213              : interface AgentCrdtFollowerEvents {
     214              :   onAppliedUpdate?: (event: {
     215              :     workflowId: string
     216              :     opIds: readonly string[]
     217              :     isLive: boolean
     218              :   }) => void
     219              :   onMaterialized?: (event: {
     220              :     workflowId: string
     221              :     actor: string | undefined
     222              :     nodeIds: readonly NodeId[]
     223              :   }) => void
     224              :   onReset?: (workflowId: string) => void
     225              :   onLineageConfirmed?: (event: {
     226              :     workflowId: string
     227              :     lineageSeq: number
     228              :   }) => void
     229              :   /**
     230              :    * PM-1604 / BE-11437: the doc-host classified a resync refusal as
     231              :    * permanent (one of `PERMANENT_SUBSCRIBE_REFUSAL_CODES`) — the lifecycle
     232              :    * has already stopped retrying it, so this is the one chance to tell the
     233              :    * person their canvas is out of sync instead of leaving them to notice a
     234              :    * channel that silently stopped updating. Not fired for `unsupported`
     235              :    * (the doc surface is off for this deployment; every user hits it, so it
     236              :    * latches silently) or for a refusal that repeats on reconnect for a
     237              :    * workflow already notified. `code` is the doc-host's permanent refusal
     238              :    * code (e.g. `schema_version_mismatch`, `catalog_mismatch`) so the
     239              :    * presentation layer can choose accurate localized copy instead of a
     240              :    * single message for every permanent reason.
     241              :    */
     242              :   onSyncError?: (message?: string, code?: string) => void
     243              : }
     244              : 
     245            0 : function notifyAppliedUpdate(
     246              :   update: ClassifiedDocUpdate,
     247              :   outcome: FrameOutcome,
     248              :   events: AgentCrdtFollowerEvents
     249              : ): void {
     250            0 :   if (!outcome.applied || outcome.failureCount > 0) return
     251            0 :   events.onAppliedUpdate?.({
     252              :     workflowId: update.workflowId,
     253              :     opIds: update.opIds ?? [],
     254              :     isLive: !update.catchUp
     255              :   })
     256              : }
     257              : 
     258            0 : function notifyLineageConfirmed(
     259              :   detail: { workflowId?: string; lineageSeq?: number },
     260              :   events: AgentCrdtFollowerEvents
     261              : ): void {
     262            0 :   if (detail.workflowId === undefined || detail.lineageSeq === undefined) return
     263            0 :   events.onLineageConfirmed?.({
     264              :     workflowId: detail.workflowId,
     265              :     lineageSeq: detail.lineageSeq
     266              :   })
     267              : }
     268              : 
     269              : // Nothing is re-thrown: an error escaping onBeforeUnmount reaches Vue's
     270              : // logError, which re-throws in dev/test builds (this app registers no
     271              : // app.config.errorHandler) and aborts the rest of unmountComponent - leaving
     272              : // this composable's watch alive to rebind against destroyed objects.
     273            0 : function runFollowerTeardown(cleanups: readonly (() => void)[]): void {
     274            0 :   for (const cleanup of cleanups) {
     275            0 :     try {
     276            0 :       cleanup()
     277              :     } catch (error) {
     278            0 :       reportError(error, {
     279              :         surface: 'agent',
     280              :         errorType: 'failure_tearing_down_agent_crdt_follower'
     281              :       })
     282              :     }
     283              :   }
     284              : }
     285              : 
     286              : type AgentCrdtApplierDeps = Omit<
     287              :   LiveGraphApplierDeps,
     288              :   'getGraph' | 'holdsLocalWrite'
     289              : >
     290              : 
     291              : export interface AgentCrdtFollowerOptions {
     292              :   transport: AgentDocFrameTransport
     293              :   userId?: () => string | null
     294              :   isTargetActive?: Ref<boolean>
     295              :   /**
     296              :    * Live graph the document is applied to. Reactive reads inside the getter
     297              :    * are tracked, so a `null` → graph flip syncs the graph from the document
     298              :    * without waiting for the next remote frame.
     299              :    */
     300              :   getGraph?: () => LGraph | null
     301              :   events?: AgentCrdtFollowerEvents
     302              :   applierDeps?: AgentCrdtApplierDeps
     303              :   canvasFor?: (workflowId: string) => Record<string, unknown> | null
     304              :   knownLineageFor?: (workflowId: string) => number | null
     305              : }
     306              : 
     307            1 : export function useAgentCrdtFollower(
     308              :   workflowId: Ref<string | null>,
     309              :   {
     310              :     transport,
     311              :     userId = () => null,
     312              :     isTargetActive = ref(true),
     313              :     getGraph = () => null,
     314              :     events = {},
     315              :     applierDeps = {},
     316              :     canvasFor = () => null,
     317              :     knownLineageFor = () => null
     318              :   }: AgentCrdtFollowerOptions
     319              : ) {
     320            1 :   const productGate = useAgentPanelStore()
     321            1 :   const follower = shallowRef<ReturnType<typeof startAgentCrdtFollower>>()
     322            1 :   const disabledStatus: AgentCrdtStatus = {
     323              :     enabled: false,
     324              :     connected: false,
     325              :     canvasMayBeStale: false,
     326              :     workflowId: null,
     327              :     updatesApplied: 0,
     328              :     lastFrameType: null,
     329              :     terminal: null,
     330              :     outcomes: {
     331              :       received: 0,
     332              :       applied: 0,
     333              :       appliedLive: 0,
     334              :       skipped: 0,
     335              :       errored: 0,
     336              :       gap: 0,
     337              :       reset: 0,
     338              :       dropped: 0
     339              :     }
     340              :   }
     341            1 :   const status = computed(() => follower.value?.status.value ?? disabledStatus)
     342              : 
     343            1 :   watch(
     344              :     () => productGate.enabled,
     345              :     (enabled, _previous, onCleanup) => {
     346            1 :       if (!enabled) return
     347            1 :       const scope = effectScope()
     348            1 :       onCleanup(() => {
     349            0 :         follower.value = undefined
     350            0 :         scope.stop()
     351              :       })
     352            1 :       follower.value = scope.run(() =>
     353              :         startAgentCrdtFollower(workflowId, {
     354              :           transport,
     355              :           userId,
     356              :           isTargetActive,
     357              :           getGraph,
     358              :           events,
     359              :           applierDeps,
     360              :           canvasFor,
     361              :           knownLineageFor
     362              :         })
     363              :       )
     364              :     },
     365              :     { immediate: true, flush: 'sync' }
     366              :   )
     367              : 
     368            1 :   return {
     369              :     status: readonly(status),
     370              :     debugSnapshot: (): CrdtDebugSnapshot =>
     371              :       follower.value?.debugSnapshot() ??
     372              :       readCrdtSnapshot(null, {
     373              :         status: status.value,
     374              :         tabId: null,
     375              :         lastSeq: null,
     376              :         schemaError: null
     377              :       }),
     378              :     enqueueHumanOperations: (operations: GraphOperation[]) =>
     379              :       follower.value?.enqueueHumanOperations(operations),
     380              :     noteUnboundLocalIntent: (target?: string) =>
     381              :       follower.value?.noteUnboundLocalIntent(target),
     382              :     retrySubscription: () => follower.value?.retrySubscription(),
     383              :     docInputNames: (nodeId: NodeId) =>
     384              :       follower.value?.docInputNames(nodeId) ?? null,
     385              :     docWidgetValue: (nodeId: NodeId, widgetName: string) =>
     386              :       follower.value?.docWidgetValue(nodeId, widgetName),
     387              :     docPromotedWidgets: (nodeId: NodeId) =>
     388              :       follower.value?.docPromotedWidgets(nodeId) ?? null,
     389              :     mayWritePromotedHost: (nodeId: NodeId) =>
     390              :       follower.value?.mayWritePromotedHost(nodeId) ?? false,
     391              :     docHasSubgraphDefinition: (definitionId: string) =>
     392              :       follower.value?.docHasSubgraphDefinition(definitionId) ?? false,
     393              :     notifyWidgetWriteRefused: (nodeId: string | number, widgetName: string) =>
     394              :       follower.value?.notifyWidgetWriteRefused(nodeId, widgetName),
     395              :     subscriptionSent: () => follower.value?.subscriptionSent() ?? false
     396              :   }
     397              : }
     398              : 
     399            1 : function startAgentCrdtFollower(
     400              :   workflowId: Ref<string | null>,
     401              :   {
     402              :     transport,
     403              :     userId,
     404              :     isTargetActive,
     405              :     getGraph,
     406              :     events,
     407              :     applierDeps,
     408              :     canvasFor,
     409              :     knownLineageFor
     410              :   }: Required<AgentCrdtFollowerOptions>
     411              : ) {
     412            1 :   const connected = ref(false)
     413            1 :   let catchUpAwaitingProjectionFor: string | null = null
     414            1 :   const syncCanvasMayBeStale = ref(false)
     415            1 :   const projectionFailureFor = ref<string | null>(null)
     416            1 :   const canvasMayBeStale = computed(
     417              :     () => syncCanvasMayBeStale.value || projectionFailureFor.value !== null
     418              :   )
     419            1 :   const terminal = ref<AgentCrdtTerminalState>(null)
     420            1 :   const updatesApplied = ref(0)
     421            1 :   const lastFrameType = ref<string | null>(null)
     422            1 :   const subscribedWorkflowId = ref<string | null>(null)
     423            1 :   const outcomes = ref<AgentCrdtOutcomeCounters>({
     424              :     received: 0,
     425              :     applied: 0,
     426              :     appliedLive: 0,
     427              :     skipped: 0,
     428              :     errored: 0,
     429              :     gap: 0,
     430              :     reset: 0,
     431              :     dropped: 0
     432              :   })
     433              : 
     434            1 :   const client = new DocFrameClient(createLoggedTransport(transport))
     435            1 :   const bridge = new LayoutFollowerBridge(client)
     436            1 :   const lifecycle = new AgentCrdtDocLifecycle(
     437              :     () => subscribedWorkflowId.value,
     438              :     () => bridge.resubscribe(),
     439              :     (reason) => {
     440            0 :       connected.value = false
     441            0 :       terminal.value = reason
     442              :     }
     443              :   )
     444            1 :   const tabId = createUuidv4()
     445            1 :   const ownActor = (): string => `human:${userId() ?? 'anonymous'}:${tabId}`
     446              :   // Doc node ids whose human delete the host has applied but whose effect
     447              :   // frame has not yet removed them from the doc. Kept pending for the
     448              :   // reconcile so the result-to-effect window cannot resurrect them.
     449            1 :   const confirmedDeletes = new Set<string>()
     450            1 :   const rejectedOpNotifier = createRejectedOpNotifier()
     451            1 :   const sentAddsByDoc = new WeakMap<typeof bridge.follower.doc, Set<string>>()
     452            1 :   const sentAddsToCurrentDoc = (): Set<string> => {
     453            0 :     const doc = bridge.follower.doc
     454            0 :     const sentAdds = sentAddsByDoc.get(doc) ?? new Set<string>()
     455            0 :     sentAddsByDoc.set(doc, sentAdds)
     456            0 :     return sentAdds
     457              :   }
     458            1 :   const projection = new AgentCrdtProjection(getGraph, applierDeps)
     459            1 :   const pendingRejected = new Map<string, Op[]>()
     460              : 
     461            0 :   function markCanvasStale(): void {
     462            0 :     syncCanvasMayBeStale.value = true
     463            0 :     catchUpAwaitingProjectionFor = null
     464              :   }
     465              : 
     466            0 :   function markProjectionStale(workflowId: string): void {
     467            0 :     projectionFailureFor.value = workflowId
     468              :   }
     469              : 
     470            0 :   function clearProjectionStaleness(workflowId: string): void {
     471            0 :     if (projectionFailureFor.value === workflowId)
     472            0 :       projectionFailureFor.value = null
     473              :   }
     474              : 
     475            0 :   function clearSyncStaleness(): void {
     476            0 :     syncCanvasMayBeStale.value = false
     477            0 :     catchUpAwaitingProjectionFor = null
     478              :   }
     479              : 
     480            0 :   function followerDocIsBehind(): boolean {
     481            0 :     return (
     482              :       bridge.isCatchingUp ||
     483              :       (syncCanvasMayBeStale.value && catchUpAwaitingProjectionFor === null)
     484              :     )
     485              :   }
     486              : 
     487            0 :   function clearCanvasStaleness(): void {
     488            0 :     syncCanvasMayBeStale.value = false
     489            0 :     projectionFailureFor.value = null
     490            0 :     catchUpAwaitingProjectionFor = null
     491              :   }
     492              : 
     493            1 :   const applyRejectedOps = (
     494              :     workflowId: string,
     495              :     rejected: readonly Op[],
     496              :     seq: number = bridge.lastSequence
     497              :   ): boolean => {
     498            0 :     if (getGraph() === null) return false
     499            0 :     const projectionOutcome = projection.revertRejected(workflowId, rejected)
     500            0 :     if (!projectionOutcome.applied) return true
     501            0 :     reportMaterialized(workflowId, projectionOutcome.createdNodeIds)
     502            0 :     reportAgentProjection(
     503              :       {
     504              :         opIds: rejected.map((op) => op.op_id),
     505              :         seq
     506              :       },
     507              :       'reverted',
     508              :       projectionOutcome
     509              :     )
     510            0 :     return true
     511              :   }
     512              : 
     513            1 :   const drainRejectedOps = (workflowId: string): void => {
     514            0 :     const rejected = pendingRejected.get(workflowId)
     515            0 :     if (!rejected) return
     516            0 :     if (applyRejectedOps(workflowId, rejected))
     517            0 :       pendingRejected.delete(workflowId)
     518              :   }
     519              : 
     520            1 :   const trackAcknowledgedDeletes = (
     521              :     outcome: Extract<BatchOutcome, { state: 'acknowledged' }>
     522              :   ) => {
     523            0 :     const applied = new Set(outcome.result.applied)
     524            0 :     for (const op of outcome.ops) {
     525            0 :       if (op.op === 'delete_node' && applied.has(op.op_id))
     526            0 :         confirmedDeletes.add(String(op.node_id))
     527              :     }
     528            0 :     rejectedOpNotifier.notify(outcome.ops, outcome.result)
     529              :   }
     530              : 
     531            1 :   const revertRejectedOps = (
     532              :     workflowId: string,
     533              :     rejected: readonly Op[],
     534              :     seq: number | undefined
     535              :   ) => {
     536            0 :     if (isTargetActive.value && applyRejectedOps(workflowId, rejected, seq))
     537            0 :       return
     538            0 :     pendingRejected.set(workflowId, [
     539              :       ...(pendingRejected.get(workflowId) ?? []),
     540              :       ...rejected
     541              :     ])
     542              :   }
     543              : 
     544            1 :   const classifyLostEdits = ({
     545              :     ops,
     546              :     result,
     547              :     resent
     548              :   }: Extract<BatchOutcome, { state: 'acknowledged' }>): LostEdits => {
     549            0 :     const dropped = new Set(result.lwwDropped)
     550            0 :     const skipped = new Set(resent ? result.skipped : [])
     551            0 :     return {
     552              :       overwritten: ops.filter((op) => dropped.has(op.op_id)),
     553              :       unconfirmed: ops.filter(
     554              :         (op) => skipped.has(op.op_id) && !dropped.has(op.op_id)
     555              :       )
     556              :     }
     557              :   }
     558              : 
     559            1 :   const refreshCanonicalDocument = (workflowId: string): void => {
     560            0 :     if (!isTargetActive.value || workflowId !== subscribedWorkflowId.value)
     561            0 :       return
     562            0 :     heldForWorkflowId = workflowId
     563            0 :     sender.suspend()
     564            0 :     lifecycle.refresh()
     565              :   }
     566              : 
     567            1 :   const compensateAcknowledgedOps = (
     568              :     outcome: Extract<BatchOutcome, { state: 'acknowledged' }>
     569              :   ) => {
     570            0 :     const { result } = outcome
     571            0 :     const lost = classifyLostEdits(outcome)
     572            0 :     const anyLost = lost.overwritten.length + lost.unconfirmed.length > 0
     573            0 :     if (anyLost) rejectedOpNotifier.notifyLostEdits(result, lost)
     574            0 :     const applied = new Set(result.applied)
     575            0 :     const reverted = result.ok
     576              :       ? [...lost.overwritten, ...lost.unconfirmed]
     577              :       : outcome.ops.filter((op) => !applied.has(op.op_id))
     578            0 :     const workflowId = result.workflowId ?? bridge.subscribedWorkflowId
     579            0 :     if (workflowId === null || (result.ok && !anyLost)) return
     580            0 :     revertRejectedOps(workflowId, reverted, result.seq)
     581            0 :     if (anyLost) refreshCanonicalDocument(workflowId)
     582              :   }
     583              : 
     584            1 :   const workflowsWithUnsyncedOps = new Set<string>()
     585            1 :   const recordUnsynced = (): void => {
     586            0 :     const unsynced = new Set(workflowsWithUnsyncedOps)
     587            0 :     for (const { workflowId } of sender.pendingOps()) unsynced.add(workflowId)
     588            0 :     recordUnsyncedHumanOps(tabId, unsynced)
     589              :   }
     590            1 :   const noteSettledHumanOps = (
     591              :     outcome: BatchOutcome,
     592              :     workflowId: string | null
     593              :   ): void => {
     594            0 :     if (workflowId !== null && outcome.state !== 'acknowledged')
     595            0 :       workflowsWithUnsyncedOps.add(workflowId)
     596            0 :     recordUnsynced()
     597              :   }
     598              : 
     599            1 :   const settleHumanOps = (outcome: BatchOutcome, workflowId: string | null) => {
     600            0 :     if (outcome.state === 'acknowledged') {
     601            0 :       trackAcknowledgedDeletes(outcome)
     602            0 :       recordDevEvent('human_ops_settled', outcome)
     603              :     }
     604            0 :     projection.settleLocalWrites(outcome.ops)
     605            0 :     if (outcome.state === 'acknowledged') compensateAcknowledgedOps(outcome)
     606            0 :     noteSettledHumanOps(outcome, workflowId)
     607              :   }
     608              : 
     609            1 :   let counterReadFailureReported = false
     610            1 :   const sender = createOpSender({
     611              :     sendOps: (target, tab, ops) =>
     612              :       !followerDocIsBehind() && client.sendOps(target, tab, ops),
     613              :     onOpsResult(listener) {
     614            1 :       const handler: EventListener = (event) => {
     615              :         // `docFrameClient` already validated this into a DocOpsResult, which
     616              :         // OpsResultView is derived from, so it travels whole.
     617            0 :         if (event instanceof CustomEvent)
     618            0 :           listener(event.detail as OpsResultView)
     619              :       }
     620            1 :       bridge.addEventListener('doc_ops_result', handler)
     621            1 :       return () => bridge.removeEventListener('doc_ops_result', handler)
     622              :     },
     623              :     // Send REALITY, not this composable's intent: the sender re-reads it before
     624              :     // every send and resend, so ops never reach a doc we are not subscribed to.
     625              :     workflowId: () => bridge.subscribedWorkflowId,
     626              :     get tab() {
     627            0 :       return tabId
     628              :     },
     629              :     actor: ownActor,
     630              :     baseVersion: () => bridge.lastSequence,
     631              :     observedCounter: () => {
     632            0 :       try {
     633            0 :         return observedDocCounter(bridge.follower.doc)
     634              :       } catch (error) {
     635            0 :         if (
     636              :           !counterReadFailureReported &&
     637              :           !(error instanceof SchemaVersionError)
     638              :         ) {
     639            0 :           counterReadFailureReported = true
     640            0 :           reportError(error, {
     641              :             surface: 'agent',
     642              :             errorType: 'failure_reading_agent_doc_counter',
     643              :             tags: {
     644              :               feature_area: 'agent',
     645              :               operation: 'sync',
     646              :               outcome: 'degraded'
     647              :             },
     648              :             level: 'warning'
     649              :           })
     650              :         }
     651            0 :         return undefined
     652              :       }
     653              :     },
     654              :     onBatchSettled: settleHumanOps
     655              :   })
     656            1 :   const coalescer = createOpCoalescer((operations) => {
     657            0 :     sender.admit(operations)
     658            0 :     recordUnsynced()
     659              :   }, sender.flush)
     660              : 
     661            1 :   const pendingLiveNodeIds = new Set<NodeId>()
     662            1 :   const pendingProjectionFrames = new Map<string, ProjectionFrameId[]>()
     663            1 :   const reportMaterialized = (
     664              :     workflowId: string,
     665              :     materialized: readonly NodeId[]
     666              :   ): void => {
     667            0 :     emitPendingMaterializations(
     668              :       workflowId,
     669              :       undefined,
     670              :       new Set(materialized),
     671              :       pendingLiveNodeIds,
     672              :       events
     673              :     )
     674              :   }
     675            1 :   const retainPendingFrame = (update: ClassifiedDocUpdate): void => {
     676            0 :     const frames = pendingProjectionFrames.get(update.workflowId)
     677            0 :     const frame = {
     678              :       opIds: update.opIds,
     679              :       seq: update.seq,
     680              :       isLive: !update.catchUp
     681              :     }
     682            0 :     if (frames) frames.push(frame)
     683            0 :     else pendingProjectionFrames.set(update.workflowId, [frame])
     684              :   }
     685            1 :   const reportPendingFrames = (
     686              :     workflowId: string,
     687              :     stage: Extract<AgentGraphProjectionStage, 'applied_deferred' | 'discarded'>,
     688              :     outcome: FrameOutcome
     689              :   ): void => {
     690            0 :     const frames = pendingProjectionFrames.get(workflowId)
     691            0 :     pendingProjectionFrames.delete(workflowId)
     692            0 :     for (const frame of frames ?? [])
     693            0 :       reportAgentProjection(frame, stage, outcome)
     694              :   }
     695            1 :   const notifyPendingFramesApplied = (
     696              :     workflowId: string,
     697              :     frames: readonly ProjectionFrameId[]
     698              :   ): void => {
     699            0 :     for (const frame of frames) {
     700            0 :       events.onAppliedUpdate?.({
     701              :         workflowId,
     702              :         opIds: frame.opIds ?? [],
     703              :         isLive: frame.isLive ?? true
     704              :       })
     705              :     }
     706              :   }
     707            1 :   const flushPendingFrames = (
     708              :     workflowId: string,
     709              :     outcome: FrameOutcome
     710              :   ): void => {
     711            0 :     if (projectionAppliedCleanly(outcome))
     712            0 :       notifyPendingFramesApplied(
     713              :         workflowId,
     714              :         pendingProjectionFrames.get(workflowId) ?? []
     715              :       )
     716            0 :     reportPendingFrames(workflowId, 'applied_deferred', outcome)
     717              :   }
     718            1 :   const reportFrameProjection = (
     719              :     update: ClassifiedDocUpdate,
     720              :     outcome: FrameOutcome
     721              :   ): void => {
     722            0 :     const stage = outcome.applied
     723              :       ? 'applied'
     724              :       : getGraph() === null
     725              :         ? 'received_no_graph'
     726              :         : 'discarded'
     727            0 :     if (isAgentFrame(update.actor)) {
     728              :       const reported = stage === 'discarded' ? NOTHING_APPLIED : outcome
     729            0 :       reportAgentProjection(update, stage, reported)
     730              :     }
     731            0 :     if (stage === 'received_no_graph') {
     732            0 :       if (isAgentFrame(update.actor)) retainPendingFrame(update)
     733            0 :       return
     734              :     }
     735            0 :     if (stage === 'applied') flushPendingFrames(update.workflowId, outcome)
     736            0 :     else reportPendingFrames(update.workflowId, 'discarded', NOTHING_APPLIED)
     737              :   }
     738            1 :   const settleCollectedProjection = (
     739              :     workflowId: string,
     740              :     outcome: Extract<FrameOutcome, { applied: true }>,
     741              :     pendingFrames: readonly ProjectionFrameId[]
     742              :   ): void => {
     743            0 :     if (outcome.failureCount > 0) {
     744            0 :       markProjectionStale(workflowId)
     745            0 :       return
     746              :     }
     747            0 :     notifyPendingFramesApplied(workflowId, pendingFrames)
     748            0 :     if (!projection.hasPendingFailure(workflowId))
     749            0 :       clearProjectionStaleness(workflowId)
     750              :   }
     751            1 :   const applyCollected = (workflowId: string): void => {
     752            0 :     const pendingFrames = pendingProjectionFrames.get(workflowId) ?? []
     753            0 :     const outcome = projection.applyCollected(workflowId)
     754            0 :     if (!outcome.applied) return
     755            0 :     const settlesCatchUp = catchUpAwaitingProjectionFor === workflowId
     756            0 :     settleCollectedProjection(workflowId, outcome, pendingFrames)
     757            0 :     if (settlesCatchUp) clearSyncStaleness()
     758            0 :     reportMaterialized(workflowId, outcome.createdNodeIds)
     759            0 :     reportPendingFrames(workflowId, 'applied_deferred', outcome)
     760              :   }
     761            1 :   const incrementOutcome = (
     762              :     key: 'received' | 'applied' | 'appliedLive' | 'skipped' | 'reset'
     763              :   ): void => {
     764            0 :     outcomes.value = { ...outcomes.value, [key]: outcomes.value[key] + 1 }
     765              :   }
     766            1 :   const isCurrentWorkflow = (workflowId: unknown): workflowId is string =>
     767              :     isTargetActive.value && workflowId === subscribedWorkflowId.value
     768              :   /**
     769              :    * The host echoes this tab's own ops back as a `doc_update`. The graph
     770              :    * already holds that edit (the intent was minted from it), so the frame is
     771              :    * merged into the doc and never re-applied. Catch-up frames are exempt:
     772              :    * they can carry this actor as the last writer while replaying state the
     773              :    * graph has not seen.
     774              :    */
     775            1 :   const isOwnEcho = (update: ClassifiedDocUpdate): boolean =>
     776              :     !update.catchUp && update.actor === ownActor()
     777            1 :   const applyFrame = (update: ClassifiedDocUpdate): FrameOutcome => {
     778            0 :     if (isOwnEcho(update) && getGraph() !== null) {
     779            0 :       const nodes = projection.discardPending(update.workflowId)
     780            0 :       incrementOutcome('skipped')
     781            0 :       return { applied: false, nodes }
     782              :     }
     783            0 :     const outcome = projection.applyFrame(update)
     784            0 :     incrementOutcome(outcome.applied ? 'applied' : 'skipped')
     785            0 :     if (outcome.applied && !update.catchUp) incrementOutcome('appliedLive')
     786            0 :     return outcome
     787              :   }
     788              : 
     789            0 :   function tryReseed(): boolean {
     790            0 :     const target = subscribedWorkflowId.value
     791            0 :     if (target === null || !bridge.canReseed(target)) return false
     792            0 :     const canvas = canvasFor(target)
     793            0 :     if (!hasNodes(canvas) || !bridge.reseed(target, canvas)) return false
     794            0 :     recordDevEvent('doc_reseed_sent', { workflowId: target })
     795            0 :     lifecycle.onSubscribeSent(target)
     796            0 :     return true
     797              :   }
     798            1 :   const onReseedResult: EventListener = (event) => {
     799            0 :     if (!(event instanceof CustomEvent)) return
     800            0 :     const detail = event.detail as {
     801              :       workflowId?: unknown
     802              :       ok?: unknown
     803              :       code?: unknown
     804              :     } | null
     805            0 :     if (!isCurrentWorkflow(detail?.workflowId)) return
     806            0 :     lastFrameType.value = event.type
     807            0 :     recordDevEvent('doc_reseed_result', detail)
     808            0 :     const code = typeof detail.code === 'string' ? detail.code : undefined
     809            0 :     if (detail.ok === true || code === RESEED_CONFLICT) return
     810            0 :     if (isRetryableReseedCode(code)) lifecycle.onSubscribeRefused(code)
     811              :     else {
     812            0 :       lifecycle.stopProbing()
     813            0 :       terminal.value = 'refused'
     814              :     }
     815              :   }
     816              : 
     817            0 :   function handleRejectedSubscription(
     818              :     detail: {
     819              :       workflowId?: unknown
     820              :       ok?: unknown
     821              :       code?: unknown
     822              :       message?: unknown
     823              :     } | null
     824              :   ): void {
     825            0 :     const reseeding = tryReseed()
     826            0 :     const refusal = reseeding
     827              :       ? { shouldNotify: false }
     828              :       : handleSubscribeRefusal(detail, lifecycle)
     829            0 :     if (
     830              :       !reseeding &&
     831              :       refusal.code !== undefined &&
     832              :       isPermanentSubscribeRefusalCode(refusal.code) &&
     833              :       lifecycle.refusalIsFinal()
     834              :     )
     835            0 :       terminal.value = 'refused'
     836            0 :     sender.abortIfUnbound('subscribe_refused')
     837            0 :     releaseHeldOps()
     838            0 :     if (refusal.shouldNotify)
     839            0 :       events.onSyncError?.(refusal.message, refusal.code)
     840              :   }
     841              : 
     842            0 :   function subscribeBaselineIsIntegrated(seq: number | undefined): boolean {
     843            0 :     return (seq ?? 0) === 0 || bridge.isSubscribeBaselineIntegrated
     844              :   }
     845              : 
     846            0 :   function retryFailedProjection(workflowId: string): boolean {
     847            0 :     const outcome = projection.retryFailed(workflowId)
     848            0 :     if (outcome === null) {
     849            0 :       const pending =
     850              :         projection.hasPendingFailure(workflowId) ||
     851              :         (getGraph() === null && projectionFailureFor.value === workflowId)
     852            0 :       if (!pending) clearProjectionStaleness(workflowId)
     853            0 :       return !pending
     854              :     }
     855            0 :     reportMaterialized(workflowId, outcome.createdNodeIds)
     856            0 :     if (outcome.failureCount === 0) {
     857            0 :       clearProjectionStaleness(workflowId)
     858            0 :       return true
     859              :     }
     860            0 :     markProjectionStale(workflowId)
     861            0 :     return false
     862              :   }
     863              : 
     864            1 :   const onSubscribed: EventListener = (event) => {
     865            0 :     if (!(event instanceof CustomEvent)) return
     866            0 :     if (!isTargetActive.value) return
     867            0 :     const detail = event.detail as {
     868              :       ok?: unknown
     869              :       code?: unknown
     870              :       message?: unknown
     871              :       seq?: number
     872              :       workflowId?: string
     873              :       lineageSeq?: number
     874              :     } | null
     875            0 :     const ok = detail?.ok === true
     876            0 :     connected.value = ok
     877            0 :     lastFrameType.value = event.type
     878            0 :     recordDevEvent('doc_subscribed', event.detail ?? null)
     879            0 :     if (ok) {
     880            0 :       notifyLineageConfirmed(detail, events)
     881            0 :       const workflowId = subscribedWorkflowId.value
     882            0 :       const projectionIsClean =
     883              :         workflowId === null || retryFailedProjection(workflowId)
     884            0 :       if (subscribeBaselineIsIntegrated(detail.seq)) {
     885            0 :         if (projectionIsClean) clearCanvasStaleness()
     886              :         else {
     887            0 :           clearSyncStaleness()
     888            0 :           markProjectionStale(workflowId)
     889              :         }
     890              :       }
     891            0 :       terminal.value = null
     892            0 :       lifecycle.onSubscribeConfirmed()
     893            0 :       forgetUnsyncedAtLoad(subscribedWorkflowId.value)
     894            0 :       resumeHeldOpsIfSubscribed()
     895            0 :       sender.retryTransport()
     896              :     } else {
     897            0 :       handleRejectedSubscription(detail)
     898              :     }
     899              :   }
     900            0 :   function settleCatchUpProjection(
     901              :     update: ClassifiedDocUpdate,
     902              :     outcome: FrameOutcome
     903              :   ): void {
     904            0 :     if (outcome.applied ? outcome.failureCount > 0 : getGraph() === null) {
     905            0 :       markProjectionStale(update.workflowId)
     906            0 :     } else if (
     907              :       projectionAppliedCleanly(outcome) &&
     908              :       !projection.hasPendingFailure(update.workflowId)
     909              :     ) {
     910            0 :       clearProjectionStaleness(update.workflowId)
     911              :     }
     912            0 :     if (!update.catchUp) return
     913            0 :     if (outcome.applied) clearSyncStaleness()
     914            0 :     else catchUpAwaitingProjectionFor = update.workflowId
     915            0 :     sender.retryTransport()
     916              :   }
     917            1 :   const onUpdate: EventListener = (event) => {
     918            0 :     if (!(event instanceof CustomEvent)) return
     919            0 :     const update = event.detail as ClassifiedDocUpdate
     920            0 :     incrementOutcome('received')
     921            0 :     if (!isCurrentWorkflow(update.workflowId)) {
     922            0 :       incrementOutcome('skipped')
     923            0 :       return
     924              :     }
     925            0 :     lifecycle.onDocumentUpdate()
     926            0 :     updatesApplied.value = bridge.follower.updatesApplied
     927            0 :     lastFrameType.value = event.type
     928            0 :     retryFailedProjection(update.workflowId)
     929            0 :     const outcome = applyFrame(update)
     930            0 :     settleCatchUpProjection(update, outcome)
     931            0 :     notifyAppliedUpdate(update, outcome, events)
     932            0 :     const nodes = outcome.nodes
     933            0 :     const created = outcome.applied ? outcome.createdNodeIds : []
     934            0 :     reportFrameProjection(update, outcome)
     935            0 :     recordDevEvent('doc_update', {
     936              :       workflowId: update.workflowId,
     937              :       seq: update.seq,
     938              :       actor: update.actor,
     939              :       echo: isOwnEcho(update),
     940              :       bytes: update.update instanceof Uint8Array ? update.update.length : null
     941              :     })
     942            0 :     if (nodes.added.length > 0 || nodes.removed.length > 0)
     943            0 :       recordDevEvent('doc_nodes_changed', nodes)
     944            0 :     notifyAgentMaterialization(
     945              :       update,
     946              :       nodes,
     947              :       created,
     948              :       getGraph(),
     949              :       pendingLiveNodeIds,
     950              :       events
     951              :     )
     952              :   }
     953            1 :   const onOpsResult: EventListener = (event) => {
     954            0 :     if (!(event instanceof CustomEvent)) return
     955            0 :     const detail = event.detail as { workflowId?: unknown } | null
     956            0 :     const dropReason = opsResultDropReason(
     957              :       isTargetActive.value,
     958              :       detail?.workflowId,
     959              :       subscribedWorkflowId.value
     960              :     )
     961            0 :     if (dropReason !== null) {
     962            0 :       recordDevEvent('doc_ops_result_dropped', {
     963              :         reason: dropReason,
     964              :         subscribedWorkflowId: subscribedWorkflowId.value,
     965              :         frame: event.detail ?? null
     966              :       })
     967            0 :       return
     968              :     }
     969            0 :     lifecycle.onDocumentResult()
     970            0 :     lastFrameType.value = event.type
     971            0 :     recordDevEvent('doc_ops_result', event.detail ?? null)
     972              :   }
     973            1 :   const onDocReset: EventListener = (event) => {
     974            0 :     const detail =
     975              :       event instanceof CustomEvent
     976              :         ? (event.detail as { workflowId?: string })
     977              :         : undefined
     978            0 :     incrementOutcome('reset')
     979            0 :     if (!isCurrentWorkflow(detail?.workflowId)) return
     980            0 :     projection.replaceOnNextFrame(detail.workflowId)
     981            0 :     reportPendingFrames(detail.workflowId, 'discarded', NOTHING_APPLIED)
     982            0 :     sender.abortAll()
     983            0 :     workflowsWithUnsyncedOps.delete(detail.workflowId)
     984            0 :     recordUnsynced()
     985            0 :     events.onReset?.(detail.workflowId)
     986            0 :     connected.value = false
     987            0 :     markCanvasStale()
     988            0 :     updatesApplied.value = 0
     989            0 :     lastFrameType.value = event.type
     990            0 :     lifecycle.clearStaleProbe()
     991            0 :     lifecycle.resetNotifiedGiveUp()
     992            0 :     pendingLiveNodeIds.clear()
     993            0 :     recordDevEvent(
     994              :       'doc_reset',
     995              :       event instanceof CustomEvent ? (event.detail ?? null) : null
     996              :     )
     997              :   }
     998            1 :   const onFollowerReplaced: EventListener = (event) => {
     999              :     // Gate on this composable's own INTENT, not the bridge's send REALITY
    1000              :     // (`bridge.subscribedWorkflowId`): a doc replacement while the socket is
    1001              :     // down leaves reality null, but the adapter must still be rebound to the
    1002              :     // new doc — otherwise it keeps observing the destroyed one and goes deaf
    1003              :     // when the socket recovers and updates land in the replacement.
    1004            0 :     if (!(event instanceof CustomEvent)) return
    1005              :     const detail = event.detail as { workflowId?: unknown } | null
    1006            0 :     const workflowId = detail?.workflowId
    1007            0 :     if (
    1008              :       isTargetActive.value &&
    1009              :       typeof workflowId === 'string' &&
    1010              :       workflowId === subscribedWorkflowId.value
    1011              :     ) {
    1012            0 :       updatesApplied.value = 0
    1013            0 :       projection.discardPending(workflowId)
    1014            0 :       reportPendingFrames(workflowId, 'discarded', NOTHING_APPLIED)
    1015            0 :       projection.bind(workflowId, bridge.follower)
    1016              :     }
    1017              :   }
    1018            1 :   const staleClientNotified = new Set<string>()
    1019            1 :   const onSchemaError: EventListener = (event) => {
    1020            0 :     connected.value = false
    1021            0 :     markCanvasStale()
    1022            0 :     terminal.value = 'schema_error'
    1023            0 :     lastFrameType.value = event.type
    1024            0 :     lifecycle.clearStaleProbe()
    1025            0 :     const detail =
    1026              :       event instanceof CustomEvent
    1027              :         ? (event.detail as { workflowId?: string; found?: unknown } | null)
    1028              :         : null
    1029            0 :     if (detail?.workflowId !== undefined) {
    1030            0 :       projection.discardPending(detail.workflowId)
    1031            0 :       reportPendingFrames(detail.workflowId, 'discarded', NOTHING_APPLIED)
    1032              :     }
    1033            0 :     outcomes.value = { ...outcomes.value, errored: outcomes.value.errored + 1 }
    1034            0 :     recordDevEvent(
    1035              :       'schema_error',
    1036              :       event instanceof CustomEvent ? (event.detail ?? null) : null
    1037              :     )
    1038            0 :     notifyStaleClient(detail)
    1039              :   }
    1040            0 :   function notifyStaleClient(
    1041              :     detail: { workflowId?: string; found?: unknown } | null
    1042              :   ): void {
    1043            0 :     const found = detail?.found
    1044            0 :     const skew = docSchemaSkew(found)
    1045            0 :     const workflowId = detail?.workflowId
    1046            0 :     if (skew === null || workflowId === undefined) return
    1047            0 :     const notificationKey = `${workflowId}:${skew}`
    1048            0 :     if (staleClientNotified.has(notificationKey)) return
    1049            0 :     staleClientNotified.add(notificationKey)
    1050            0 :     if (skew === 'newer') {
    1051            0 :       events.onSyncError?.(
    1052              :         `document schema v${found} is newer than this page reads (v${SCHEMA_VERSION})`,
    1053              :         'stale_client_schema'
    1054              :       )
    1055            0 :       return
    1056              :     }
    1057            0 :     events.onSyncError?.(
    1058              :       `document schema v${found} is older than this page reads (v${SCHEMA_VERSION})`,
    1059              :       'stale_host_schema'
    1060              :     )
    1061              :   }
    1062            1 :   const onGap: EventListener = (event) => {
    1063            0 :     connected.value = false
    1064            0 :     markCanvasStale()
    1065            0 :     outcomes.value = { ...outcomes.value, gap: outcomes.value.gap + 1 }
    1066            0 :     recordDevEvent(
    1067              :       'doc_gap',
    1068              :       event instanceof CustomEvent ? (event.detail ?? null) : null
    1069              :     )
    1070              :   }
    1071            1 :   const onStale: EventListener = (event) => {
    1072            0 :     outcomes.value = { ...outcomes.value, dropped: outcomes.value.dropped + 1 }
    1073            0 :     recordDevEvent(
    1074              :       'doc_stale',
    1075              :       event instanceof CustomEvent ? (event.detail ?? null) : null
    1076              :     )
    1077              :   }
    1078            1 :   const onSubscribeSent: EventListener = (event) => {
    1079            0 :     if (!(event instanceof CustomEvent)) return
    1080            0 :     const detail = event.detail as { workflowId?: unknown } | null
    1081            0 :     if (typeof detail?.workflowId !== 'string') return
    1082            0 :     lifecycle.onSubscribeSent(detail.workflowId)
    1083              :   }
    1084            2 :   function onSocketStatus(live: boolean): void {
    1085            2 :     if (!live) {
    1086            1 :       if (connected.value) markCanvasStale()
    1087            1 :       connected.value = false
    1088            1 :       return
    1089              :     }
    1090            1 :     connected.value = false
    1091            1 :     terminal.value = null
    1092            1 :     lifecycle.onReconnected()
    1093            1 :     recordDevEvent('reconnected', null)
    1094            1 :     bridge.reconnect()
    1095              :   }
    1096              : 
    1097            1 :   bridge.addEventListener('doc_subscribed', onSubscribed)
    1098            1 :   bridge.addEventListener('doc_update', onUpdate)
    1099            1 :   bridge.addEventListener('doc_ops_result', onOpsResult)
    1100            1 :   bridge.addEventListener('doc_reset', onDocReset)
    1101            1 :   bridge.addEventListener('follower_replaced', onFollowerReplaced)
    1102            1 :   bridge.addEventListener('schema_error', onSchemaError)
    1103            1 :   bridge.addEventListener('doc_gap', onGap)
    1104            1 :   bridge.addEventListener('doc_stale', onStale)
    1105            1 :   bridge.addEventListener('doc_subscribe_sent', onSubscribeSent)
    1106            1 :   bridge.addEventListener('doc_reseed_result', onReseedResult)
    1107            1 :   const stopTransportStatus = transport.onSocketStatus(onSocketStatus)
    1108              : 
    1109              :   // FE-1902 (poc-3): distinguish the mount-time null (in-memory doc id died
    1110              :   // with the previous mount — rebind from sessionStorage) from a later null
    1111              :   // (a REAL detach, e.g. new chat — drop the persisted id too).
    1112            1 :   let initialBind = true
    1113              :   // Readiness only. The other ordering -- graph ready first, target activated
    1114              :   // second -- cannot be caught here: `getGraph` does not change when activity
    1115              :   // flips, and even if this watcher also took `isTargetActive` as a source it
    1116              :   // was created before the binding watcher below, so it would run first and
    1117              :   // still see no subscribed workflow. Activation therefore applies what was
    1118              :   // collected at the bind site instead, once the binding actually exists.
    1119            1 :   watch(getGraph, (graph) => {
    1120            0 :     const bound = subscribedWorkflowId.value
    1121            0 :     if (graph && bound !== null && isTargetActive.value) {
    1122            0 :       applyCollected(bound)
    1123            0 :       drainRejectedOps(bound)
    1124              :     }
    1125              :   })
    1126            1 :   const rebindProjection = (next: string | null): void => {
    1127            1 :     const current = subscribedWorkflowId.value
    1128            1 :     if (current === next) return
    1129            0 :     clearCanvasStaleness()
    1130            0 :     if (current !== null) {
    1131            0 :       projection.unbind(current)
    1132            0 :       reportPendingFrames(current, 'discarded', NOTHING_APPLIED)
    1133              :     }
    1134            0 :     if (next !== null) projection.bind(next, bridge.follower)
    1135            0 :     subscribedWorkflowId.value = next
    1136              :   }
    1137              :   // The bound workflow whose tab went inactive while the sender still held
    1138              :   // batches for it. A tab switch pauses the subscription without rebinding
    1139              :   // the session, so those batches are held rather than aborted (see
    1140              :   // ADR-CRDT-WRITE-0035); anything else that moves the binding releases
    1141              :   // them into the normal abort path.
    1142            1 :   let heldForWorkflowId: string | null = null
    1143            1 :   const releaseHeldOps = (): void => {
    1144            1 :     heldForWorkflowId = null
    1145            1 :     sender.resume()
    1146              :   }
    1147            1 :   const resumeHeldOpsIfSubscribed = (): void => {
    1148            0 :     if (
    1149              :       heldForWorkflowId !== null &&
    1150              :       bridge.subscribedWorkflowId === heldForWorkflowId
    1151              :     ) {
    1152            0 :       releaseHeldOps()
    1153              :     }
    1154              :   }
    1155            1 :   const holdOpsForInactiveTab = (workflowId: string): void => {
    1156            0 :     heldForWorkflowId = workflowId
    1157            0 :     sender.suspend()
    1158            0 :     bridge.unsubscribe()
    1159              :   }
    1160              :   // Flush first: an edit admitted this tick is pinned to the doc still bound
    1161              :   // here, and the coalescer's deferred flush would otherwise find it unbound.
    1162              :   // Then drive the bridge's intent and give the sender the same eager signal
    1163              :   // the refusal branch gets: `reconcile()` clears send reality synchronously
    1164              :   // when the desired doc changes, and a batch minted for the old doc would
    1165              :   // otherwise wait out the 10 s result-silence window before noticing. The
    1166              :   // one exception is the workflow whose ops are held: its subscribe may not
    1167              :   // have left a closed socket yet, so the abort waits for the ack instead.
    1168            1 :   const retarget = (next: string | null): void => {
    1169            1 :     sender.flush()
    1170            1 :     if (next === null) bridge.unsubscribe()
    1171              :     else {
    1172            0 :       const knownLineage = knownLineageFor(next)
    1173            0 :       if (knownLineage === null) bridge.subscribe(next)
    1174            0 :       else bridge.subscribe(next, knownLineage)
    1175              :     }
    1176            1 :     if (next !== null && next === heldForWorkflowId) {
    1177            0 :       resumeHeldOpsIfSubscribed()
    1178            0 :       return
    1179              :     }
    1180            1 :     sender.abortIfUnbound('retarget')
    1181            1 :     releaseHeldOps()
    1182              :   }
    1183              : 
    1184              :   // A tab switch keeps the projection bound: whatever the doc collects while
    1185              :   // the tab is away is applied on return, instead of the live graph being
    1186              :   // rebuilt from the whole doc over the human's edits.
    1187            1 :   const deactivateTarget = (
    1188              :     next: string | null,
    1189              :     previousWorkflowId: string | null
    1190              :   ): void => {
    1191            1 :     if (next !== null) initialBind = false
    1192            1 :     if (next !== null && next === previousWorkflowId) {
    1193            0 :       if (connected.value || canvasMayBeStale.value) markCanvasStale()
    1194            0 :       connected.value = false
    1195            0 :       holdOpsForInactiveTab(next)
    1196            0 :       return
    1197              :     }
    1198            1 :     connected.value = false
    1199            1 :     rebindProjection(null)
    1200            1 :     retarget(null)
    1201              :   }
    1202              : 
    1203            1 :   const restorePersistedTarget = (justActivated: boolean): void => {
    1204            0 :     const persisted = initialBind ? lifecycle.readPersistedDocId() : null
    1205            0 :     initialBind = false
    1206            0 :     if (persisted === null) {
    1207            0 :       lifecycle.clearPersistedDocId()
    1208            0 :       rebindProjection(null)
    1209            0 :       retarget(null)
    1210            0 :       return
    1211              :     }
    1212            0 :     recordDevEvent('rebind', { workflowId: persisted })
    1213            0 :     rebindProjection(persisted)
    1214            0 :     retarget(persisted)
    1215            0 :     if (justActivated) applyCollected(persisted)
    1216              :   }
    1217              : 
    1218              :   type TargetSnapshot = [string | null | undefined, boolean | undefined]
    1219            1 :   const isActivationEdge = (
    1220              :     active: boolean,
    1221              :     previous: TargetSnapshot | undefined
    1222              :   ): boolean => active && previous?.[1] === false
    1223            1 :   const acknowledgesFollowedDoc = (
    1224              :     next: string | null,
    1225              :     active: boolean,
    1226              :     justActivated: boolean
    1227              :   ): boolean =>
    1228              :     active &&
    1229              :     !justActivated &&
    1230              :     next !== null &&
    1231              :     next === subscribedWorkflowId.value
    1232              : 
    1233            1 :   const activateTarget = (next: string, justActivated: boolean): void => {
    1234            0 :     initialBind = false
    1235            0 :     rebindProjection(next)
    1236            0 :     retarget(next)
    1237            0 :     drainRejectedOps(next)
    1238            0 :     if (justActivated) applyCollected(next)
    1239              :   }
    1240              : 
    1241            1 :   watch(
    1242              :     [workflowId, isTargetActive],
    1243              :     ([next, active], previous: TargetSnapshot | undefined) => {
    1244            1 :       const justActivated = isActivationEdge(active, previous)
    1245            1 :       if (acknowledgesFollowedDoc(next, active, justActivated)) return
    1246            1 :       lifecycle.clearForRetarget()
    1247            1 :       terminal.value = null
    1248            1 :       pendingLiveNodeIds.clear()
    1249            1 :       if (!active) {
    1250            1 :         deactivateTarget(next, previous?.[0] ?? null)
    1251            1 :         return
    1252              :       }
    1253            0 :       connected.value = false
    1254            0 :       if (next === null) {
    1255            0 :         restorePersistedTarget(justActivated)
    1256            0 :         return
    1257              :       }
    1258            0 :       activateTarget(next, justActivated)
    1259              :     },
    1260              :     { immediate: true }
    1261              :   )
    1262              : 
    1263            1 :   onScopeDispose(() => {
    1264              :     // Teardown must be total. Anything that survives would apply every later
    1265              :     // update twice after a remount.
    1266            0 :     runFollowerTeardown([
    1267              :       () => lifecycle.destroy(),
    1268              :       () => stopTransportStatus(),
    1269              :       () => bridge.removeEventListener('doc_subscribed', onSubscribed),
    1270              :       () => bridge.removeEventListener('doc_update', onUpdate),
    1271              :       () => bridge.removeEventListener('doc_ops_result', onOpsResult),
    1272              :       () => bridge.removeEventListener('doc_reset', onDocReset),
    1273              :       () => bridge.removeEventListener('follower_replaced', onFollowerReplaced),
    1274              :       () => bridge.removeEventListener('schema_error', onSchemaError),
    1275              :       () => bridge.removeEventListener('doc_gap', onGap),
    1276              :       () => bridge.removeEventListener('doc_stale', onStale),
    1277              :       () => bridge.removeEventListener('doc_subscribe_sent', onSubscribeSent),
    1278              :       () => bridge.removeEventListener('doc_reseed_result', onReseedResult),
    1279              :       () => sender.detach(),
    1280              :       () => pendingRejected.clear(),
    1281              :       () => coalescer.detach(),
    1282              :       () => {
    1283            0 :         for (const workflowId of pendingProjectionFrames.keys())
    1284            0 :           reportPendingFrames(workflowId, 'discarded', NOTHING_APPLIED)
    1285            0 :         projection.destroy()
    1286              :       },
    1287              :       () => bridge.destroy(),
    1288              :       () => client.destroy()
    1289              :     ])
    1290            0 :     releaseUnsyncedHumanOpsRecorder(tabId)
    1291              :   })
    1292              : 
    1293            1 :   const status = computed<AgentCrdtStatus>(() => ({
    1294              :     enabled: true,
    1295              :     connected: connected.value,
    1296              :     canvasMayBeStale: canvasMayBeStale.value,
    1297              :     workflowId: subscribedWorkflowId.value,
    1298              :     terminal: terminal.value,
    1299              :     updatesApplied: updatesApplied.value,
    1300              :     lastFrameType: lastFrameType.value,
    1301              :     outcomes: outcomes.value
    1302              :   }))
    1303              : 
    1304            1 :   const debugSnapshot = (): CrdtDebugSnapshot =>
    1305              :     readCrdtSnapshot(bridge.follower.doc, {
    1306              :       status: status.value,
    1307              :       tabId,
    1308              :       lastSeq: bridge.lastSequence,
    1309              :       schemaError: bridge.lastSchemaError?.message ?? null
    1310              :     })
    1311              : 
    1312            1 :   return {
    1313              :     status: readonly(status),
    1314              :     debugSnapshot,
    1315              :     retrySubscription: () => {
    1316            0 :       if (!lifecycle.retry()) return
    1317            0 :       connected.value = false
    1318            0 :       terminal.value = null
    1319              :     },
    1320              :     enqueueHumanOperations: (operations: GraphOperation[]) => {
    1321            0 :       const sentAdds = sentAddsToCurrentDoc()
    1322            0 :       for (const operation of operations)
    1323            0 :         if (operation.op === 'add_node') sentAdds.add(String(operation.node_id))
    1324            0 :       projection.noteLocalWrites(operations)
    1325            0 :       coalescer.enqueue(operations)
    1326              :     },
    1327              :     noteUnboundLocalIntent: (target = workflowId.value) => {
    1328            0 :       if (target === null) return
    1329            0 :       workflowsWithUnsyncedOps.add(target)
    1330            0 :       recordUnsynced()
    1331              :     },
    1332              :     docInputNames: (nodeId: NodeId) =>
    1333              :       readDocSlotNames(bridge.follower.doc, String(nodeId), 'inputs'),
    1334              :     docWidgetValue: (nodeId: NodeId, widgetName: string) =>
    1335              :       readDocWidgetValue(bridge.follower.doc, String(nodeId), widgetName),
    1336              :     docPromotedWidgets: (nodeId: NodeId) =>
    1337              :       readDocPromotedWidgets(bridge.follower.doc, String(nodeId)),
    1338              :     mayWritePromotedHost: (nodeId: NodeId) =>
    1339              :       bridge.isSubscribeBaselineIntegrated ||
    1340              :       (sentAddsToCurrentDoc().has(String(nodeId)) &&
    1341              :         readDocPromotedWidgets(bridge.follower.doc, String(nodeId)) === null),
    1342              :     docHasSubgraphDefinition: (definitionId: string) =>
    1343              :       readSubgraphDefinitionIds(bridge.follower.doc).includes(definitionId),
    1344              :     notifyWidgetWriteRefused: (nodeId: string | number, widgetName: string) =>
    1345              :       rejectedOpNotifier.notifyWidgetWriteRefused(nodeId, widgetName),
    1346              :     subscriptionSent: () =>
    1347              :       bridge.subscribedWorkflowId !== null &&
    1348              :       bridge.subscribedWorkflowId === subscribedWorkflowId.value
    1349              :   }
    1350              : }
    1351              : 
    1352            0 : function docSchemaSkew(found: unknown): 'newer' | 'older' | null {
    1353            0 :   if (typeof found !== 'number' || !Number.isInteger(found) || found <= 0)
    1354            0 :     return null
    1355            0 :   if (found > SCHEMA_VERSION) return 'newer'
    1356            0 :   if (found < SCHEMA_VERSION) return 'older'
    1357            0 :   return null
    1358              : }
        

Generated by: LCOV version 2.0-1