From cc4950a8ebe7bedbd87c05505f90435ce052ef30 Mon Sep 17 00:00:00 2001 From: Amp Date: Mon, 31 Aug 2026 09:44:23 +0000 Subject: [PATCH 01/37] feat(agent): add GraphDocument registry and activation seam Implements the ADR-0024 document/activation seam for the in-app agent: - DocumentId brand and target-keyed GraphDocument registry (workflow_id -> document_id mapping, duplicate/stale rejection) - pure document lifecycle reducer with derived persistence state, save tickets, and CAS close - activation coordinator with generation-raced activate/deactivate and ordered view-binding handoff - detached target session: staged unloaded-target frame queue with all-or-nothing commit, last-committed state-vector recovery, doc_reset lineage, gap/duplicate/overflow handling - target frame projection port: atomic clear+rebuild snapshot batch through GraphMutations - renderer-independent canonical document serializer - byte-identical save/reload integration tests across activation cycles, stamp/incarnation preservation, active-canvas isolation, reconnect/reset coverage - early-bound document identity in AgentPanelRoot scope resolution Amp-Thread-ID: https://ampcode.com/threads/T-01a05717-75a6-77a8-a59a-3ba204aa654c --- .../document/activationCoordinator.test.ts | 165 ++++++++ .../graph/document/activationCoordinator.ts | 89 +++++ .../document/detachedTargetSession.test.ts | 333 ++++++++++++++++ .../graph/document/detachedTargetSession.ts | 255 ++++++++++++ .../graph/document/documentLifecycle.test.ts | 143 +++++++ src/core/graph/document/documentLifecycle.ts | 74 ++++ src/core/graph/document/documentSerializer.ts | 59 +++ src/stores/graphDocumentStore.test.ts | 180 +++++++++ src/stores/graphDocumentStore.ts | 210 ++++++++++ src/types/documentId.ts | 18 + .../extensions/agent/AgentPanelRoot.vue | 29 +- ...tActivationPersistence.integration.test.ts | 364 ++++++++++++++++++ .../agent/crdt/targetFrameProjection.ts | 139 +++++++ 13 files changed, 2052 insertions(+), 6 deletions(-) create mode 100644 src/core/graph/document/activationCoordinator.test.ts create mode 100644 src/core/graph/document/activationCoordinator.ts create mode 100644 src/core/graph/document/detachedTargetSession.test.ts create mode 100644 src/core/graph/document/detachedTargetSession.ts create mode 100644 src/core/graph/document/documentLifecycle.test.ts create mode 100644 src/core/graph/document/documentLifecycle.ts create mode 100644 src/core/graph/document/documentSerializer.ts create mode 100644 src/stores/graphDocumentStore.test.ts create mode 100644 src/stores/graphDocumentStore.ts create mode 100644 src/types/documentId.ts create mode 100644 src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts create mode 100644 src/workbench/extensions/agent/crdt/targetFrameProjection.ts diff --git a/src/core/graph/document/activationCoordinator.test.ts b/src/core/graph/document/activationCoordinator.test.ts new file mode 100644 index 00000000000..94c9506be5c --- /dev/null +++ b/src/core/graph/document/activationCoordinator.test.ts @@ -0,0 +1,165 @@ +import { describe, expect, it } from 'vitest' + +import type { DocumentViewBinding } from '@/core/graph/document/activationCoordinator' +import { createActivationCoordinator } from '@/core/graph/document/activationCoordinator' +import type { DocumentId } from '@/types/documentId' +import { toDocumentId } from '@/types/documentId' + +function recordingBinding(log: string[], name: string): DocumentViewBinding { + return { + attach: (id: DocumentId) => log.push(`attach:${name}:${id}`), + detach: (id: DocumentId) => log.push(`detach:${name}:${id}`) + } +} + +function deferred(): { promise: Promise; resolve: () => void } { + let resolve!: () => void + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +describe('createActivationCoordinator', () => { + it('activates a loaded document and publishes it as active', async () => { + const coordinator = createActivationCoordinator({ isLoaded: () => true }) + const log: string[] = [] + const docA = toDocumentId('doc-a') + + const outcome = await coordinator.activate(docA, recordingBinding(log, 'a')) + + expect(outcome).toEqual({ status: 'activated', documentId: docA }) + expect(coordinator.activeDocumentId()).toBe(docA) + expect(log).toEqual([`attach:a:${docA}`]) + }) + + it('rejects activation of a document that is not loaded', async () => { + const coordinator = createActivationCoordinator({ isLoaded: () => false }) + const log: string[] = [] + const docA = toDocumentId('doc-a') + + const outcome = await coordinator.activate(docA, recordingBinding(log, 'a')) + + expect(outcome).toEqual({ + status: 'rejected', + documentId: docA, + reason: 'not-loaded' + }) + expect(coordinator.activeDocumentId()).toBeNull() + expect(log).toEqual([]) + }) + + it('rejects when hydration fails and leaves the previous binding intact', async () => { + const docA = toDocumentId('doc-a') + const docB = toDocumentId('doc-b') + const coordinator = createActivationCoordinator({ + isLoaded: () => true, + hydrate: (id) => + id === docB ? Promise.reject(new Error('boom')) : Promise.resolve() + }) + const log: string[] = [] + await coordinator.activate(docA, recordingBinding(log, 'a')) + + const outcome = await coordinator.activate(docB, recordingBinding(log, 'b')) + + expect(outcome).toEqual({ + status: 'rejected', + documentId: docB, + reason: 'hydration-failed' + }) + expect(coordinator.activeDocumentId()).toBe(docA) + expect(log).toEqual([`attach:a:${docA}`]) + }) + + it('performs an ordered detach-then-attach handoff between documents', async () => { + const coordinator = createActivationCoordinator({ isLoaded: () => true }) + const log: string[] = [] + const docA = toDocumentId('doc-a') + const docB = toDocumentId('doc-b') + + await coordinator.activate(docA, recordingBinding(log, 'a')) + await coordinator.activate(docB, recordingBinding(log, 'b')) + + expect(log).toEqual([ + `attach:a:${docA}`, + `detach:a:${docA}`, + `attach:b:${docB}` + ]) + expect(coordinator.activeDocumentId()).toBe(docB) + }) + + it('supersedes a slow activate when a newer activate wins the race', async () => { + const slowHydration = deferred() + const docA = toDocumentId('doc-a') + const docB = toDocumentId('doc-b') + const coordinator = createActivationCoordinator({ + isLoaded: () => true, + hydrate: (id) => (id === docA ? slowHydration.promise : Promise.resolve()) + }) + const log: string[] = [] + + const first = coordinator.activate(docA, recordingBinding(log, 'a')) + const second = await coordinator.activate(docB, recordingBinding(log, 'b')) + slowHydration.resolve() + const firstOutcome = await first + + expect(second).toEqual({ status: 'activated', documentId: docB }) + expect(firstOutcome).toEqual({ status: 'superseded', documentId: docA }) + expect(coordinator.activeDocumentId()).toBe(docB) + expect(log).toEqual([`attach:b:${docB}`]) + }) + + it('reports superseded when a stale request fails hydration after being overtaken', async () => { + const slowHydration = deferred() + const docA = toDocumentId('doc-a') + const docB = toDocumentId('doc-b') + const coordinator = createActivationCoordinator({ + isLoaded: () => true, + hydrate: (id) => + id === docA + ? slowHydration.promise.then(() => { + throw new Error('late failure') + }) + : Promise.resolve() + }) + const log: string[] = [] + + const first = coordinator.activate(docA, recordingBinding(log, 'a')) + await coordinator.activate(docB, recordingBinding(log, 'b')) + slowHydration.resolve() + + expect(await first).toEqual({ status: 'superseded', documentId: docA }) + expect(coordinator.activeDocumentId()).toBe(docB) + }) + + it('deactivate detaches the active document and cancels in-flight activation', async () => { + const slowHydration = deferred() + const docA = toDocumentId('doc-a') + const docB = toDocumentId('doc-b') + const coordinator = createActivationCoordinator({ + isLoaded: () => true, + hydrate: (id) => (id === docB ? slowHydration.promise : Promise.resolve()) + }) + const log: string[] = [] + await coordinator.activate(docA, recordingBinding(log, 'a')) + + const inFlight = coordinator.activate(docB, recordingBinding(log, 'b')) + expect(coordinator.deactivate(docA)).toBe(true) + slowHydration.resolve() + + expect(await inFlight).toEqual({ status: 'superseded', documentId: docB }) + expect(coordinator.activeDocumentId()).toBeNull() + expect(log).toEqual([`attach:a:${docA}`, `detach:a:${docA}`]) + }) + + it('deactivate of a non-active document is a no-op', async () => { + const coordinator = createActivationCoordinator({ isLoaded: () => true }) + const log: string[] = [] + const docA = toDocumentId('doc-a') + const docB = toDocumentId('doc-b') + await coordinator.activate(docA, recordingBinding(log, 'a')) + + expect(coordinator.deactivate(docB)).toBe(false) + expect(coordinator.activeDocumentId()).toBe(docA) + }) +}) diff --git a/src/core/graph/document/activationCoordinator.ts b/src/core/graph/document/activationCoordinator.ts new file mode 100644 index 00000000000..00f9bf23eff --- /dev/null +++ b/src/core/graph/document/activationCoordinator.ts @@ -0,0 +1,89 @@ +import type { DocumentId } from '@/types/documentId' + +/** + * View concerns attached by activation and detached by deactivation: the + * renderer/canvas binding, render-attached caches, viewport projection, and + * input/event hooks. Attach and detach must not touch semantic document + * state (ADR-0024: activation is presentation). + */ +export interface DocumentViewBinding { + attach(documentId: DocumentId): void + detach(documentId: DocumentId): void +} + +export type ActivationOutcome = + | { status: 'activated'; documentId: DocumentId } + /** A newer activate/deactivate request won the generation race. */ + | { status: 'superseded'; documentId: DocumentId } + | { + status: 'rejected' + documentId: DocumentId + reason: 'not-loaded' | 'hydration-failed' + } + +export interface ActivationCoordinatorDeps { + /** The registry's loaded check for the document being activated. */ + isLoaded(documentId: DocumentId): boolean + /** + * Hydrate and validate the document before the handoff. Runs without + * changing the current binding; a stale request discards this staged work. + */ + hydrate?(documentId: DocumentId): Promise +} + +/** + * Serializes document activation onto the active-canvas binding (ADR-0024). + * Requests carry a monotonic generation: a newer request cancels any older + * in-flight one, and a stale request may clean up its private staged work + * but can never detach, attach, or publish. The winning request performs one + * ordered handoff — detach the previous document's view hooks, attach the + * new document's, publish the new active binding — so a late `activate(A)` + * completion cannot overwrite a later `activate(B)`. + */ +export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { + let generation = 0 + let active: { documentId: DocumentId; binding: DocumentViewBinding } | null = + null + + async function activate( + documentId: DocumentId, + binding: DocumentViewBinding + ): Promise { + const requestGeneration = ++generation + const stale = (): boolean => requestGeneration !== generation + try { + await deps.hydrate?.(documentId) + } catch { + return stale() + ? { status: 'superseded', documentId } + : { status: 'rejected', documentId, reason: 'hydration-failed' } + } + if (stale()) return { status: 'superseded', documentId } + if (!deps.isLoaded(documentId)) + return { status: 'rejected', documentId, reason: 'not-loaded' } + + if (active) active.binding.detach(active.documentId) + binding.attach(documentId) + active = { documentId, binding } + return { status: 'activated', documentId } + } + + /** + * Explicit inverse of {@link activate}. Detaches view concerns only; the + * document remains loaded and its domain stores, follower, queue, change + * tracking, and persistence continue to operate. + */ + function deactivate(documentId: DocumentId): boolean { + if (active?.documentId !== documentId) return false + generation++ + active.binding.detach(documentId) + active = null + return true + } + + function activeDocumentId(): DocumentId | null { + return active?.documentId ?? null + } + + return { activate, deactivate, activeDocumentId } +} diff --git a/src/core/graph/document/detachedTargetSession.test.ts b/src/core/graph/document/detachedTargetSession.test.ts new file mode 100644 index 00000000000..d3f3d2e0e38 --- /dev/null +++ b/src/core/graph/document/detachedTargetSession.test.ts @@ -0,0 +1,333 @@ +import { describe, expect, it } from 'vitest' +import * as Y from 'yjs' + +import type { + TargetFrame, + TargetFrameApplyPort +} from '@/core/graph/document/detachedTargetSession' +import { createDetachedTargetSession } from '@/core/graph/document/detachedTargetSession' + +const WORKFLOW_ID = 'wf-detached' + +/** + * A host document emitting ordered incremental update frames, mirroring the + * doc_update stream a live host produces. + */ +function createFrameSource(workflowId = WORKFLOW_ID) { + const host = new Y.Doc() + let seq = 0 + let lastVector = Y.encodeStateVector(host) + + function frame( + mutate: (doc: Y.Doc) => void, + stamps: Pick = {} + ): TargetFrame { + mutate(host) + const update = Y.encodeStateAsUpdate(host, lastVector) + lastVector = Y.encodeStateVector(host) + seq += 1 + return { workflowId, seq, update, ...stamps } + } + + function diffFrom(stateVector: Uint8Array, atSeq: number): TargetFrame { + return { + workflowId, + seq: atSeq, + update: Y.encodeStateAsUpdate(host, stateVector) + } + } + + return { host, frame, diffFrom } +} + +function setNode(doc: Y.Doc, id: string, fields: Record) { + const nodes = doc.getMap>('nodes') + const node = nodes.get(id) ?? new Y.Map() + if (!nodes.has(id)) nodes.set(id, node) + for (const [key, value] of Object.entries(fields)) node.set(key, value) +} + +function readNodes(update: Uint8Array): Record { + const doc = new Y.Doc() + Y.applyUpdate(doc, update) + const json = doc.getMap('nodes').toJSON() + doc.destroy() + return json +} + +const acceptAll: TargetFrameApplyPort = { apply: () => true } +const rejectAll: TargetFrameApplyPort = { apply: () => false } + +describe('createDetachedTargetSession', () => { + it('commits queued frames in order and reproduces the host state byte-exactly', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID) + + session.enqueue( + source.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + session.enqueue(source.frame((doc) => setNode(doc, '1', { title: 'a' }))) + session.enqueue(source.frame((doc) => setNode(doc, '2', { type: 'Sink' }))) + + const drained = session.drainAll(acceptAll) + + expect(drained).toEqual({ committed: 3, stoppedBy: { status: 'idle' } }) + expect(readNodes(session.encodeCommittedState())).toEqual( + source.host.getMap('nodes').toJSON() + ) + const snapshot = session.snapshot() + expect(snapshot.committedSeq).toBe(3) + expect(snapshot.revision).toBe(3) + expect(snapshot.lastCommitId).toBe(`${snapshot.lineage}:3`) + expect(snapshot.queuedFrames).toBe(0) + expect(snapshot.needsResync).toBe(false) + }) + + it('offers the projection port the frame stamps verbatim and the staged doc with the frame folded in', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID) + const seen: { frame: TargetFrame; stagedNodes: Record }[] = + [] + const port: TargetFrameApplyPort = { + apply: (frame, stagedDoc) => { + seen.push({ frame, stagedNodes: stagedDoc.getMap('nodes').toJSON() }) + return true + } + } + + const frame = source.frame((doc) => setNode(doc, '1', { type: 'Source' }), { + actor: 'agent:planner', + opIds: ['op-1', 'op-2'] + }) + session.enqueue(frame) + session.commitNext(port) + + expect(seen).toHaveLength(1) + expect(seen[0]!.frame.actor).toBe('agent:planner') + expect(seen[0]!.frame.opIds).toEqual(['op-1', 'op-2']) + expect(seen[0]!.frame.seq).toBe(1) + expect(seen[0]!.stagedNodes).toEqual({ '1': { type: 'Source' } }) + }) + + it('preserves node incarnation bytes through the staged commit path', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID) + session.enqueue( + source.frame((doc) => + setNode(doc, '9', { type: 'Source', __incarnation: 'inc-original-9' }) + ) + ) + + session.commitNext(acceptAll) + + const committed = readNodes(session.encodeCommittedState()) + expect(committed).toEqual({ + '9': { type: 'Source', __incarnation: 'inc-original-9' } + }) + expect(committed).toEqual(source.host.getMap('nodes').toJSON()) + }) + + it('a rejected apply leaves the frame queued and the committed tuple unchanged', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID) + session.enqueue( + source.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + session.commitNext(acceptAll) + const before = session.snapshot() + const vectorBefore = session.recoveryStateVector() + + session.enqueue(source.frame((doc) => setNode(doc, '1', { title: 'b' }))) + const failed = session.commitNext(rejectAll) + + expect(failed).toEqual({ status: 'failed', seq: 2 }) + expect(session.snapshot()).toEqual({ ...before, queuedFrames: 1 }) + expect(session.recoveryStateVector()).toEqual(vectorBefore) + + const retried = session.commitNext(acceptAll) + expect(retried).toEqual({ + status: 'committed', + commitId: `${before.lineage}:2`, + seq: 2 + }) + }) + + it('a throwing apply reports failed with the error and keeps the frame queued', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID) + session.enqueue( + source.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + const boom = new Error('projection exploded') + + const result = session.commitNext({ + apply: () => { + throw boom + } + }) + + expect(result).toEqual({ status: 'failed', seq: 1, error: boom }) + expect(session.snapshot().queuedFrames).toBe(1) + expect(session.snapshot().committedSeq).toBeNull() + }) + + it('skips duplicate frames at or below the last accepted sequence', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID) + const first = source.frame((doc) => setNode(doc, '1', { type: 'Source' })) + session.enqueue(first) + session.commitNext(acceptAll) + + expect(session.enqueue(first)).toEqual({ status: 'duplicate', seq: 1 }) + + const second = source.frame((doc) => setNode(doc, '1', { title: 'c' })) + session.enqueue(second) + expect(session.enqueue(second)).toEqual({ status: 'duplicate', seq: 2 }) + expect(session.snapshot().queuedFrames).toBe(1) + }) + + it('a sequence gap discards the queue, demands resync, and preserves the recovery state vector', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID) + session.enqueue( + source.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + session.commitNext(acceptAll) + const recoveryBefore = session.recoveryStateVector() + session.enqueue(source.frame((doc) => setNode(doc, '1', { title: 'q' }))) + + source.frame((doc) => setNode(doc, '1', { title: 'lost' })) + const gapFrame = source.frame((doc) => setNode(doc, '2', { type: 'Sink' })) + const result = session.enqueue(gapFrame) + + expect(result).toEqual({ status: 'gap', expectedSeq: 3, receivedSeq: 4 }) + const snapshot = session.snapshot() + expect(snapshot.needsResync).toBe(true) + expect(snapshot.queuedFrames).toBe(0) + expect(snapshot.committedSeq).toBe(1) + expect(session.recoveryStateVector()).toEqual(recoveryBefore) + expect(session.enqueue(gapFrame)).toEqual({ status: 'resync-required' }) + expect(session.commitNext(acceptAll)).toEqual({ + status: 'resync-required' + }) + }) + + it('recovers from a gap by replaying the diff against the last committed state vector', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID) + session.enqueue( + source.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + session.commitNext(acceptAll) + + source.frame((doc) => setNode(doc, '1', { title: 'lost' })) + session.enqueue(source.frame((doc) => setNode(doc, '2', { type: 'Sink' }))) + + session.beginResync() + const catchUp = source.diffFrom(session.recoveryStateVector(), 3) + expect(session.enqueue(catchUp)).toEqual({ + status: 'queued', + queuedFrames: 1 + }) + expect(session.commitNext(acceptAll).status).toBe('committed') + expect(readNodes(session.encodeCommittedState())).toEqual( + source.host.getMap('nodes').toJSON() + ) + }) + + it('overflow discards queued frames but keeps the last committed state for recovery', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID, { + maxQueuedFrames: 2 + }) + session.enqueue( + source.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + session.commitNext(acceptAll) + const recoveryBefore = session.recoveryStateVector() + + session.enqueue(source.frame((doc) => setNode(doc, '1', { title: 'a' }))) + session.enqueue(source.frame((doc) => setNode(doc, '1', { title: 'b' }))) + const overflowed = session.enqueue( + source.frame((doc) => setNode(doc, '1', { title: 'c' })) + ) + + expect(overflowed).toEqual({ status: 'overflow', discardedFrames: 2 }) + const snapshot = session.snapshot() + expect(snapshot.needsResync).toBe(true) + expect(snapshot.queuedFrames).toBe(0) + expect(snapshot.committedSeq).toBe(1) + expect(session.recoveryStateVector()).toEqual(recoveryBefore) + + session.beginResync() + session.enqueue(source.diffFrom(session.recoveryStateVector(), 4)) + session.commitNext(acceptAll) + expect(readNodes(session.encodeCommittedState())).toEqual( + source.host.getMap('nodes').toJSON() + ) + }) + + it('doc_reset starts a fresh document and lineage and invalidates old commit ids', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID) + session.enqueue( + source.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + session.commitNext(acceptAll) + const oldSnapshot = session.snapshot() + const oldCommitId = oldSnapshot.lastCommitId! + expect(session.isCommitted(oldCommitId)).toBe(true) + session.enqueue( + source.frame((doc) => setNode(doc, '1', { title: 'stale' })) + ) + + session.resetLineage(10) + + const snapshot = session.snapshot() + expect(snapshot.lineage).not.toBe(oldSnapshot.lineage) + expect(snapshot.committedSeq).toBe(10) + expect(snapshot.queuedFrames).toBe(0) + expect(snapshot.lastCommitId).toBeNull() + expect(session.isCommitted(oldCommitId)).toBe(false) + expect(readNodes(session.encodeCommittedState())).toEqual({}) + + const freshHost = new Y.Doc() + setNode(freshHost, '5', { type: 'Fresh' }) + session.enqueue({ + workflowId: WORKFLOW_ID, + seq: 11, + update: Y.encodeStateAsUpdate(freshHost) + }) + expect(session.commitNext(acceptAll).status).toBe('committed') + expect(session.snapshot().lastCommitId).toBe(`${snapshot.lineage}:11`) + freshHost.destroy() + }) + + it('rejects frames addressed to another target loudly', () => { + const session = createDetachedTargetSession(WORKFLOW_ID) + const stranger = createFrameSource('wf-other') + + expect(() => + session.enqueue( + stranger.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + ).toThrow(/frames must never cross targets/) + }) + + it('isCommitted answers for any sequence at or below the committed head of the same lineage', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID) + session.enqueue( + source.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + session.enqueue(source.frame((doc) => setNode(doc, '1', { title: 'a' }))) + session.drainAll(acceptAll) + const { lineage } = session.snapshot() + + expect(session.isCommitted(`${lineage}:1`)).toBe(true) + expect(session.isCommitted(`${lineage}:2`)).toBe(true) + expect(session.isCommitted(`${lineage}:3`)).toBe(false) + expect(session.isCommitted(`other-lineage:1`)).toBe(false) + expect(session.isCommitted('malformed')).toBe(false) + }) +}) diff --git a/src/core/graph/document/detachedTargetSession.ts b/src/core/graph/document/detachedTargetSession.ts new file mode 100644 index 00000000000..d0f24176bcc --- /dev/null +++ b/src/core/graph/document/detachedTargetSession.ts @@ -0,0 +1,255 @@ +import * as Y from 'yjs' + +import { createUuidv4 } from '@/utils/uuid' + +/** + * One ordered effect frame addressed to a target document. Structurally + * compatible with the workbench `DocUpdate` wire frame; declared here so the + * core document seam never imports workbench transport types. + */ +export interface TargetFrame { + readonly workflowId: string + readonly seq: number + readonly update: Uint8Array + readonly actor?: string + /** Accepted semantic op identities folded into this effect frame (DQ-9). */ + readonly opIds?: readonly string[] +} + +/** + * Projects one staged frame into the domain stores. `apply` receives the + * staged document with the frame already folded in; it must be all-or-nothing + * and report whether the projection committed. A `false` return (or a throw) + * leaves the frame queued and the session's committed tuple untouched. + */ +export interface TargetFrameApplyPort { + apply(frame: TargetFrame, stagedDoc: Y.Doc): boolean +} + +export type EnqueueResult = + | { status: 'queued'; queuedFrames: number } + /** `seq` at or below the last accepted frame — replay, skipped. */ + | { status: 'duplicate'; seq: number } + /** Non-contiguous `seq`; queue discarded, resync required. */ + | { status: 'gap'; expectedSeq: number; receivedSeq: number } + /** Queue bound exceeded; queue discarded, resync required. */ + | { status: 'overflow'; discardedFrames: number } + | { status: 'resync-required' } + +export type CommitResult = + | { status: 'idle' } + | { status: 'resync-required' } + | { status: 'committed'; commitId: string; seq: number } + | { status: 'failed'; seq: number; error?: unknown } + +export interface DetachedTargetSessionSnapshot { + readonly workflowId: string + readonly lineage: string + readonly committedSeq: number | null + readonly revision: number + readonly queuedFrames: number + readonly needsResync: boolean + readonly lastCommitId: string | null +} + +export interface DetachedTargetSessionOptions { + /** Upper bound on staged-but-uncommitted frames. */ + readonly maxQueuedFrames?: number + readonly initialLineage?: string +} + +const DEFAULT_MAX_QUEUED_FRAMES = 64 + +/** + * Staged frame queue for a target document that is not attached to a live + * follower (ADR-0024's unloaded-target path). Frames enqueue in wire order + * and commit one at a time: each commit folds the head frame into a clone of + * the last committed Yjs state, offers it to the projection port, and only + * on success publishes the new committed tuple + * `{revision, sequence, stateVector, lineage, lastCommitId}` and dequeues. + * + * The last committed state vector is the recovery anchor: on queue overflow + * or a sequence gap the queued frames are discarded but the committed state + * survives, so the host can be asked for exactly the missing diff + * (`recoveryStateVector`). A `doc_reset` starts a new lineage with a fresh + * document; commit identities (`lineage:seq`) from the old lineage never + * collide with the new one. + */ +export function createDetachedTargetSession( + workflowId: string, + options: DetachedTargetSessionOptions = {} +) { + const maxQueuedFrames = options.maxQueuedFrames ?? DEFAULT_MAX_QUEUED_FRAMES + + let lineage = options.initialLineage ?? createUuidv4() + let committedDoc = new Y.Doc() + let committedSeq: number | null = null + let revision = 0 + let lastCommitId: string | null = null + let needsResync = false + /** `null` accepts any sequence (fresh session or just resynced). */ + let expectedSeq: number | null = null + let queue: TargetFrame[] = [] + + function assertTarget(frameWorkflowId: string): void { + if (frameWorkflowId !== workflowId) { + throw new Error( + `DetachedTargetSession(${workflowId}) received a frame addressed to ` + + `"${frameWorkflowId}"; frames must never cross targets` + ) + } + } + + function enqueue(frame: TargetFrame): EnqueueResult { + assertTarget(frame.workflowId) + if (needsResync) return { status: 'resync-required' } + + const lastAcceptedSeq = queue.at(-1)?.seq ?? committedSeq + if (lastAcceptedSeq !== null && frame.seq <= lastAcceptedSeq) + return { status: 'duplicate', seq: frame.seq } + + if (expectedSeq !== null && frame.seq !== expectedSeq) { + const gapAt = expectedSeq + queue = [] + needsResync = true + return { status: 'gap', expectedSeq: gapAt, receivedSeq: frame.seq } + } + + if (queue.length >= maxQueuedFrames) { + const discardedFrames = queue.length + queue = [] + needsResync = true + return { status: 'overflow', discardedFrames } + } + + queue.push(frame) + expectedSeq = frame.seq + 1 + return { status: 'queued', queuedFrames: queue.length } + } + + function commitNext(port: TargetFrameApplyPort): CommitResult { + if (needsResync) return { status: 'resync-required' } + const frame = queue[0] + if (!frame) return { status: 'idle' } + + const staged = new Y.Doc() + Y.applyUpdate(staged, Y.encodeStateAsUpdate(committedDoc)) + Y.applyUpdate(staged, frame.update) + + let applied: boolean + try { + applied = port.apply(frame, staged) + } catch (error) { + staged.destroy() + return { status: 'failed', seq: frame.seq, error } + } + if (!applied) { + staged.destroy() + return { status: 'failed', seq: frame.seq } + } + + committedDoc.destroy() + committedDoc = staged + committedSeq = frame.seq + revision += 1 + lastCommitId = `${lineage}:${frame.seq}` + queue.shift() + return { status: 'committed', commitId: lastCommitId, seq: frame.seq } + } + + function drainAll(port: TargetFrameApplyPort): { + committed: number + stoppedBy: CommitResult + } { + let committed = 0 + for (;;) { + const result = commitNext(port) + if (result.status !== 'committed') return { committed, stoppedBy: result } + committed += 1 + } + } + + /** + * State vector of the last committed document state — what the host must + * diff against to replay everything this session is missing. + */ + function recoveryStateVector(): Uint8Array { + return Y.encodeStateVector(committedDoc) + } + + /** Committed Yjs state, byte-exact, for hydration into a live follower. */ + function encodeCommittedState(): Uint8Array { + return Y.encodeStateAsUpdate(committedDoc) + } + + /** + * The host has replayed the missing diff onto the committed state (or will + * send a full catch-up next); accept the next frame at any sequence. + */ + function beginResync(): void { + needsResync = false + queue = [] + expectedSeq = null + } + + /** + * `doc_reset`: the host re-minted the document, so prior updates do not + * compose with what follows. Starts a fresh document and lineage; queued + * frames from the old lineage are meaningless and dropped. + */ + function resetLineage(atSeq: number): void { + committedDoc.destroy() + committedDoc = new Y.Doc() + lineage = createUuidv4() + committedSeq = atSeq + expectedSeq = null + lastCommitId = null + needsResync = false + queue = [] + } + + function isCommitted(commitId: string): boolean { + const separator = commitId.lastIndexOf(':') + if (separator < 0) return false + const commitLineage = commitId.slice(0, separator) + const seq = Number(commitId.slice(separator + 1)) + if (!Number.isInteger(seq)) return false + return ( + commitLineage === lineage && committedSeq !== null && seq <= committedSeq + ) + } + + function snapshot(): DetachedTargetSessionSnapshot { + return { + workflowId, + lineage, + committedSeq, + revision, + queuedFrames: queue.length, + needsResync, + lastCommitId + } + } + + function destroy(): void { + committedDoc.destroy() + queue = [] + } + + return { + enqueue, + commitNext, + drainAll, + recoveryStateVector, + encodeCommittedState, + beginResync, + resetLineage, + isCommitted, + snapshot, + destroy + } +} + +export type DetachedTargetSession = ReturnType< + typeof createDetachedTargetSession +> diff --git a/src/core/graph/document/documentLifecycle.test.ts b/src/core/graph/document/documentLifecycle.test.ts new file mode 100644 index 00000000000..8c0c687ffd0 --- /dev/null +++ b/src/core/graph/document/documentLifecycle.test.ts @@ -0,0 +1,143 @@ +import { describe, expect, it } from 'vitest' + +import { + initialDocumentState, + persistenceOf, + reduceDocument +} from './documentLifecycle' +import type { DocumentEvent, DocumentTrackingState } from './documentLifecycle' + +function run( + events: readonly DocumentEvent[], + from: DocumentTrackingState = initialDocumentState +): DocumentTrackingState { + return events.reduce(reduceDocument, from) +} + +describe('reduceDocument', () => { + it('starts created and unsaved', () => { + expect(initialDocumentState.phase).toBe('created') + expect(persistenceOf(initialDocumentState)).toBe('unsaved') + }) + + it('hydrates created to loaded and ignores repeat hydration', () => { + const loaded = run([{ type: 'hydrated' }]) + expect(loaded.phase).toBe('loaded') + expect(run([{ type: 'hydrated' }], loaded)).toEqual(loaded) + }) + + it('accumulates mutations while unsaved without changing persistence', () => { + const state = run([ + { type: 'hydrated' }, + { type: 'mutated' }, + { type: 'mutated' } + ]) + expect(state.revision).toBe(2) + expect(persistenceOf(state)).toBe('unsaved') + }) + + it('a completed save makes the document clean only at the captured revision', () => { + const dirty = run([{ type: 'hydrated' }, { type: 'mutated' }]) + const clean = reduceDocument(dirty, { + type: 'saveCompleted', + atRevision: dirty.revision + }) + expect(persistenceOf(clean)).toBe('clean') + }) + + it('a mutation that commits while a save is in flight leaves the document dirty', () => { + const beforeSave = run([{ type: 'hydrated' }, { type: 'mutated' }]) + const capturedRevision = beforeSave.revision + const mutatedDuringSave = reduceDocument(beforeSave, { type: 'mutated' }) + const afterSave = reduceDocument(mutatedDuringSave, { + type: 'saveCompleted', + atRevision: capturedRevision + }) + expect(afterSave.savedRevision).toBe(capturedRevision) + expect(persistenceOf(afterSave)).toBe('dirty') + }) + + it('ignores a save completion ahead of the live revision or behind the baseline', () => { + const state = run([ + { type: 'hydrated' }, + { type: 'mutated' }, + { type: 'saveCompleted', atRevision: 1 } + ]) + expect( + reduceDocument(state, { type: 'saveCompleted', atRevision: 99 }) + ).toEqual(state) + expect( + reduceDocument(state, { type: 'saveCompleted', atRevision: 0 }) + ).toEqual(state) + }) + + it('remote or human mutations after a save make a loaded document dirty again', () => { + const state = run([ + { type: 'hydrated' }, + { type: 'mutated' }, + { type: 'saveCompleted', atRevision: 1 }, + { type: 'mutated' } + ]) + expect(persistenceOf(state)).toBe('dirty') + }) + + it('closes a clean document at its exact revision', () => { + const state = run([ + { type: 'hydrated' }, + { type: 'mutated' }, + { type: 'saveCompleted', atRevision: 1 }, + { type: 'closed', atRevision: 1, discardChanges: false } + ]) + expect(state.phase).toBe('closed') + }) + + it('refuses to close a dirty document without an explicit discard decision', () => { + const dirty = run([{ type: 'hydrated' }, { type: 'mutated' }]) + expect( + reduceDocument(dirty, { + type: 'closed', + atRevision: dirty.revision, + discardChanges: false + }).phase + ).toBe('loaded') + expect( + reduceDocument(dirty, { + type: 'closed', + atRevision: dirty.revision, + discardChanges: true + }).phase + ).toBe('closed') + }) + + it('treats a close decision as stale when the live revision moved past it', () => { + const presented = run([{ type: 'hydrated' }, { type: 'mutated' }]) + const decisionRevision = presented.revision + const moved = reduceDocument(presented, { type: 'mutated' }) + const attempted = reduceDocument(moved, { + type: 'closed', + atRevision: decisionRevision, + discardChanges: true + }) + expect(attempted.phase).toBe('loaded') + }) + + it('ignores mutation and save events after close', () => { + const closed = run([ + { type: 'hydrated' }, + { type: 'closed', atRevision: 0, discardChanges: true } + ]) + expect(reduceDocument(closed, { type: 'mutated' })).toEqual(closed) + expect( + reduceDocument(closed, { type: 'saveCompleted', atRevision: 0 }) + ).toEqual(closed) + }) + + it('cannot close a document that was never loaded', () => { + const attempted = reduceDocument(initialDocumentState, { + type: 'closed', + atRevision: 0, + discardChanges: true + }) + expect(attempted.phase).toBe('created') + }) +}) diff --git a/src/core/graph/document/documentLifecycle.ts b/src/core/graph/document/documentLifecycle.ts new file mode 100644 index 00000000000..85b97b3e0b5 --- /dev/null +++ b/src/core/graph/document/documentLifecycle.ts @@ -0,0 +1,74 @@ +/** + * The pure lifecycle/persistence transition of one `GraphDocument` + * (ADR-0024). Lifecycle (`created | loaded | closed`) and persistence + * (`unsaved | clean | dirty`) are independent: the first describes document + * existence, the second compares the document with its persistence baseline. + * Persistence is derived from `revision` vs `savedRevision`, never stored. + * + * Save capture happens outside the reducer: a caller captures + * `{ revision, bytes }` before starting I/O and reports `saveCompleted` with + * that exact revision. The baseline advances to the captured revision only, + * so mutations that commit while the save is in flight leave the document + * dirty. Close is a compare-and-set over an exact revision: a decision made + * against a revision that has since moved is stale and ignored. + */ + +type DocumentLifecyclePhase = 'created' | 'loaded' | 'closed' +export type DocumentPersistenceState = 'unsaved' | 'clean' | 'dirty' + +export interface DocumentTrackingState { + readonly phase: DocumentLifecyclePhase + /** Monotonic; incremented by every committed domain mutation. */ + readonly revision: number + /** Persistence baseline revision; `null` until the first completed save. */ + readonly savedRevision: number | null +} + +export type DocumentEvent = + | { type: 'hydrated' } + | { type: 'mutated' } + | { type: 'saveCompleted'; atRevision: number } + | { type: 'closed'; atRevision: number; discardChanges: boolean } + +export const initialDocumentState: DocumentTrackingState = { + phase: 'created', + revision: 0, + savedRevision: null +} + +export function persistenceOf( + state: DocumentTrackingState +): DocumentPersistenceState { + if (state.savedRevision === null) return 'unsaved' + return state.revision === state.savedRevision ? 'clean' : 'dirty' +} + +export function reduceDocument( + state: DocumentTrackingState, + event: DocumentEvent +): DocumentTrackingState { + switch (event.type) { + case 'hydrated': + return state.phase === 'created' ? { ...state, phase: 'loaded' } : state + case 'mutated': + return state.phase === 'closed' + ? state + : { ...state, revision: state.revision + 1 } + case 'saveCompleted': + if (state.phase === 'closed') return state + if (event.atRevision > state.revision) return state + if ( + state.savedRevision !== null && + event.atRevision < state.savedRevision + ) + return state + return { ...state, savedRevision: event.atRevision } + case 'closed': { + if (state.phase !== 'loaded') return state + if (event.atRevision !== state.revision) return state + if (!event.discardChanges && persistenceOf(state) !== 'clean') + return state + return { ...state, phase: 'closed' } + } + } +} diff --git a/src/core/graph/document/documentSerializer.ts b/src/core/graph/document/documentSerializer.ts new file mode 100644 index 00000000000..36992dd3ab8 --- /dev/null +++ b/src/core/graph/document/documentSerializer.ts @@ -0,0 +1,59 @@ +import { useLinkStore } from '@/stores/linkStore' +import { useNodeDataStore } from '@/stores/nodeDataStore' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import type { GraphScope } from '@/types/graphScopeId' +import { compareNodeIds } from '@/types/nodeId' + +const RENDER_ONLY_KEYS = new Set(['boundingRect']) + +function canonicalize(value: unknown): unknown { + if (Array.isArray(value)) return value.map(canonicalize) + if (value instanceof Map || value instanceof Set) + return canonicalize([...value]) + if (typeof value === 'object' && value !== null) { + const source = value as Record + const result: Record = {} + for (const key of Object.keys(source).sort()) { + if (RENDER_ONLY_KEYS.has(key)) continue + const entry = canonicalize(source[key]) + if (entry !== undefined) result[key] = entry + } + return result + } + return value +} + +/** + * Renderer-independent canonical serialization of one document scope's + * semantic ECS state (ADR-0024's persistence seam). Reads only the domain + * stores — never the canvas, layout, or litegraph instances — so the same + * document content produces the same bytes whether the document is active + * on the canvas, activated under a different renderer, or never activated + * at all. Byte equality of two serializations is the save/reload identity + * check. + */ +export function serializeDocumentScope(scope: GraphScope): Uint8Array { + const nodeStore = useNodeDataStore() + const linkStore = useLinkStore() + const widgetStore = useWidgetValueStore() + + const nodes = [ + ...nodeStore.getGraphNodesFor(scope.rootGraphId, scope.owningGraphId) + ] + .sort((left, right) => compareNodeIds(left.id, right.id)) + .map(({ graphId: _graphId, lastSerialization: _cache, ...semantic }) => ({ + ...semantic, + widgets: widgetStore + .getNodeWidgets(scope.rootGraphId, semantic.id) + .map(({ name, type, value }) => ({ name, type, value })) + .sort((left, right) => left.name.localeCompare(right.name)) + })) + + const links = [...linkStore.graphTopologies(scope)] + .sort((left, right) => left.id - right.id) + .map(({ graphId: _graphId, ...topology }) => topology) + + return new TextEncoder().encode( + JSON.stringify(canonicalize({ nodes, links })) + ) +} diff --git a/src/stores/graphDocumentStore.test.ts b/src/stores/graphDocumentStore.test.ts new file mode 100644 index 00000000000..313cd17d345 --- /dev/null +++ b/src/stores/graphDocumentStore.test.ts @@ -0,0 +1,180 @@ +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it } from 'vitest' + +import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' + +import { useGraphDocumentStore } from './graphDocumentStore' + +const scope = { + rootGraphId: toRootGraphId('root-a'), + owningGraphId: toOwningGraphId('root-a') +} + +describe('useGraphDocumentStore', () => { + beforeEach(() => { + setActivePinia(createPinia()) + }) + + it('creates local-only documents that are not agent-addressable', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument() + expect(documentId).not.toBeNull() + if (documentId === null) return + const entry = store.getDocument(documentId) + expect(entry?.workflowId).toBeNull() + expect(entry?.state.phase).toBe('created') + expect(store.persistenceStateOf(documentId)).toBe('unsaved') + }) + + it('resolves an agent target by workflow id, never by another key', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument({ workflowId: 'wf-1' }) + expect(documentId).not.toBeNull() + expect(store.resolveWorkflowTarget('wf-1')?.documentId).toBe(documentId) + expect(store.resolveWorkflowTarget('wf-other')).toBeNull() + }) + + it('rejects a duplicate workflow id mapping', () => { + const store = useGraphDocumentStore() + const first = store.createDocument({ workflowId: 'wf-1' }) + expect(first).not.toBeNull() + expect(store.createDocument({ workflowId: 'wf-1' })).toBeNull() + const second = store.createDocument() + if (second === null) throw new Error('createDocument failed') + expect(store.assignWorkflowId(second, 'wf-1')).toBe(false) + }) + + it('rejects a stale reassignment of a document that already has a workflow id', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument({ workflowId: 'wf-1' }) + if (documentId === null) throw new Error('createDocument failed') + expect(store.assignWorkflowId(documentId, 'wf-2')).toBe(false) + expect(store.assignWorkflowId(documentId, 'wf-1')).toBe(true) + expect(store.getDocument(documentId)?.workflowId).toBe('wf-1') + }) + + it('allows remapping a workflow id after its previous document closed', () => { + const store = useGraphDocumentStore() + const first = store.createDocument({ workflowId: 'wf-1' }) + if (first === null) throw new Error('createDocument failed') + store.hydrateDocument(first, scope) + expect( + store.closeDocument(first, { atRevision: 0, discardChanges: true }) + ).toBe(true) + expect(store.resolveWorkflowTarget('wf-1')).toBeNull() + + const second = store.createDocument() + if (second === null) throw new Error('createDocument failed') + expect(store.assignWorkflowId(second, 'wf-1')).toBe(true) + expect(store.resolveWorkflowTarget('wf-1')?.documentId).toBe(second) + }) + + it('hydration early-binds the scope without requiring a renderer', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument({ workflowId: 'wf-1' }) + if (documentId === null) throw new Error('createDocument failed') + expect(store.hydrateDocument(documentId, scope)).toBe(true) + const entry = store.getDocument(documentId) + expect(entry?.state.phase).toBe('loaded') + expect(entry?.scope).toEqual(scope) + expect(store.hydrateDocument(documentId, scope)).toBe(false) + }) + + it('rebinds scope only while loaded', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument() + if (documentId === null) throw new Error('createDocument failed') + const rebound = { + rootGraphId: toRootGraphId('root-b'), + owningGraphId: toOwningGraphId('root-b') + } + expect(store.rebindScope(documentId, rebound)).toBe(false) + store.hydrateDocument(documentId, scope) + expect(store.rebindScope(documentId, rebound)).toBe(true) + expect(store.getDocument(documentId)?.scope).toEqual(rebound) + }) + + it('tracks dirtiness across the save capture boundary', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument() + if (documentId === null) throw new Error('createDocument failed') + store.hydrateDocument(documentId, scope) + store.markMutated(documentId) + expect(store.persistenceStateOf(documentId)).toBe('unsaved') + + const ticket = store.beginSave(documentId) + expect(ticket?.revision).toBe(1) + if (!ticket) return + store.markMutated(documentId) + expect(store.completeSave(ticket)).toBe(true) + expect(store.persistenceStateOf(documentId)).toBe('dirty') + + const secondTicket = store.beginSave(documentId) + if (!secondTicket) throw new Error('beginSave failed') + expect(store.completeSave(secondTicket)).toBe(true) + expect(store.persistenceStateOf(documentId)).toBe('clean') + }) + + it('close is compare-and-set: a stale decision must be re-presented', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument() + if (documentId === null) throw new Error('createDocument failed') + store.hydrateDocument(documentId, scope) + store.markMutated(documentId) + const presentedRevision = + store.getDocument(documentId)?.state.revision ?? -1 + store.markMutated(documentId) + expect( + store.closeDocument(documentId, { + atRevision: presentedRevision, + discardChanges: true + }) + ).toBe(false) + expect(store.getDocument(documentId)?.state.phase).toBe('loaded') + expect( + store.closeDocument(documentId, { + atRevision: presentedRevision + 1, + discardChanges: true + }) + ).toBe(true) + }) + + it('refuses to close a dirty document without an explicit discard', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument() + if (documentId === null) throw new Error('createDocument failed') + store.hydrateDocument(documentId, scope) + store.markMutated(documentId) + expect( + store.closeDocument(documentId, { atRevision: 1, discardChanges: false }) + ).toBe(false) + }) + + it('removes only closed documents and clears their stale mapping', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument({ workflowId: 'wf-1' }) + if (documentId === null) throw new Error('createDocument failed') + store.hydrateDocument(documentId, scope) + expect(store.removeDocument(documentId)).toBe(false) + store.closeDocument(documentId, { atRevision: 0, discardChanges: true }) + expect(store.removeDocument(documentId)).toBe(true) + expect(store.getDocument(documentId)).toBeNull() + const next = store.createDocument({ workflowId: 'wf-1' }) + expect(next).not.toBeNull() + }) + + it('isolates state between documents: mutating A never dirties B', () => { + const store = useGraphDocumentStore() + const a = store.createDocument({ workflowId: 'wf-a' }) + const b = store.createDocument({ workflowId: 'wf-b' }) + if (a === null || b === null) throw new Error('createDocument failed') + store.hydrateDocument(a, scope) + store.hydrateDocument(b, { + rootGraphId: toRootGraphId('root-b'), + owningGraphId: toOwningGraphId('root-b') + }) + store.markMutated(a) + expect(store.getDocument(a)?.state.revision).toBe(1) + expect(store.getDocument(b)?.state.revision).toBe(0) + }) +}) diff --git a/src/stores/graphDocumentStore.ts b/src/stores/graphDocumentStore.ts new file mode 100644 index 00000000000..dfbc807a735 --- /dev/null +++ b/src/stores/graphDocumentStore.ts @@ -0,0 +1,210 @@ +import { defineStore } from 'pinia' +import { shallowReactive } from 'vue' + +import { + initialDocumentState, + persistenceOf, + reduceDocument +} from '@/core/graph/document/documentLifecycle' +import type { + DocumentPersistenceState, + DocumentTrackingState +} from '@/core/graph/document/documentLifecycle' +import type { DocumentId } from '@/types/documentId' +import { createDocumentId } from '@/types/documentId' +import type { GraphScope } from '@/types/graphScopeId' + +export interface GraphDocumentEntry { + readonly documentId: DocumentId + /** Canonical cloud wire address, when assigned. Never used as identity. */ + readonly workflowId: string | null + /** Early-bound ECS scope; set at hydration, independent of any renderer. */ + readonly scope: GraphScope | null + readonly state: DocumentTrackingState +} + +export interface SaveTicket { + readonly documentId: DocumentId + /** The exact revision whose serialized bytes the caller captured. */ + readonly revision: number +} + +/** + * The GraphDocument registry (ADR-0024): every workflow document is a + * first-class entry keyed by a stable frontend `document_id`, whether or not + * a tab, renderer, or cloud `workflow_id` exists for it. The registry owns + * the optional `workflow_id → document_id` mapping and rejects duplicate or + * stale mappings; agent frames resolve their target here and never fall back + * to the active canvas. + */ +export const useGraphDocumentStore = defineStore('graphDocument', () => { + const documents = shallowReactive(new Map()) + const documentIdByWorkflowId = shallowReactive(new Map()) + + function getDocument(documentId: DocumentId): GraphDocumentEntry | null { + return documents.get(documentId) ?? null + } + + function resolveWorkflowTarget( + workflowId: string + ): GraphDocumentEntry | null { + const documentId = documentIdByWorkflowId.get(workflowId) + if (documentId === undefined) return null + const entry = documents.get(documentId) + return entry && entry.state.phase !== 'closed' ? entry : null + } + + function persistenceStateOf( + documentId: DocumentId + ): DocumentPersistenceState | null { + const entry = documents.get(documentId) + return entry ? persistenceOf(entry.state) : null + } + + function patch( + documentId: DocumentId, + changes: Partial> + ): GraphDocumentEntry | null { + const entry = documents.get(documentId) + if (!entry) return null + const next = { ...entry, ...changes } + documents.set(documentId, next) + return next + } + + function createDocument(options?: { + workflowId?: string + }): DocumentId | null { + const workflowId = options?.workflowId ?? null + if (workflowId !== null && resolveWorkflowTarget(workflowId) !== null) + return null + const documentId = createDocumentId() + documents.set(documentId, { + documentId, + workflowId, + scope: null, + state: initialDocumentState + }) + if (workflowId !== null) documentIdByWorkflowId.set(workflowId, documentId) + return documentId + } + + /** + * Map a cloud `workflow_id` onto an existing document. Rejects a duplicate + * mapping (the workflow id already addresses another live document) and a + * stale reassignment (the document already carries a different workflow id). + */ + function assignWorkflowId( + documentId: DocumentId, + workflowId: string + ): boolean { + const entry = documents.get(documentId) + if (!entry || entry.state.phase === 'closed') return false + if (entry.workflowId === workflowId) return true + if (entry.workflowId !== null) return false + const incumbent = resolveWorkflowTarget(workflowId) + if (incumbent !== null && incumbent.documentId !== documentId) return false + documentIdByWorkflowId.set(workflowId, documentId) + patch(documentId, { workflowId }) + return true + } + + /** Transition `created → loaded` and early-bind the document's ECS scope. */ + function hydrateDocument(documentId: DocumentId, scope: GraphScope): boolean { + const entry = documents.get(documentId) + if (!entry) return false + const state = reduceDocument(entry.state, { type: 'hydrated' }) + if (state === entry.state || state.phase !== 'loaded') return false + patch(documentId, { state, scope }) + return true + } + + /** Rebind the loaded document's scope, e.g. after its graph id is reminted. */ + function rebindScope(documentId: DocumentId, scope: GraphScope): boolean { + const entry = documents.get(documentId) + if (!entry || entry.state.phase !== 'loaded') return false + patch(documentId, { scope }) + return true + } + + function markMutated(documentId: DocumentId): boolean { + const entry = documents.get(documentId) + if (!entry) return false + const state = reduceDocument(entry.state, { type: 'mutated' }) + if (state === entry.state) return false + patch(documentId, { state }) + return true + } + + /** + * Capture the save point. The caller serializes the document's bytes at + * this exact revision before starting I/O, then reports `completeSave` + * with the ticket. Mutations committed in between leave the document dirty. + */ + function beginSave(documentId: DocumentId): SaveTicket | null { + const entry = documents.get(documentId) + if (!entry || entry.state.phase === 'closed') return null + return { documentId, revision: entry.state.revision } + } + + function completeSave(ticket: SaveTicket): boolean { + const entry = documents.get(ticket.documentId) + if (!entry) return false + const state = reduceDocument(entry.state, { + type: 'saveCompleted', + atRevision: ticket.revision + }) + if (state === entry.state) return false + patch(ticket.documentId, { state }) + return true + } + + /** + * Compare-and-set close over an exact revision. Returns false when the + * decision is stale (the live revision moved) or the document is dirty + * without an explicit discard; the caller must re-present the decision. + */ + function closeDocument( + documentId: DocumentId, + decision: { atRevision: number; discardChanges: boolean } + ): boolean { + const entry = documents.get(documentId) + if (!entry) return false + const state = reduceDocument(entry.state, { + type: 'closed', + atRevision: decision.atRevision, + discardChanges: decision.discardChanges + }) + if (state.phase !== 'closed' || entry.state.phase === 'closed') return false + patch(documentId, { state, scope: null }) + return true + } + + /** Drop a closed document's registry entry and its stale mapping. */ + function removeDocument(documentId: DocumentId): boolean { + const entry = documents.get(documentId) + if (!entry || entry.state.phase !== 'closed') return false + if ( + entry.workflowId !== null && + documentIdByWorkflowId.get(entry.workflowId) === documentId + ) + documentIdByWorkflowId.delete(entry.workflowId) + documents.delete(documentId) + return true + } + + return { + createDocument, + getDocument, + resolveWorkflowTarget, + persistenceStateOf, + assignWorkflowId, + hydrateDocument, + rebindScope, + markMutated, + beginSave, + completeSave, + closeDocument, + removeDocument + } +}) diff --git a/src/types/documentId.ts b/src/types/documentId.ts new file mode 100644 index 00000000000..11f84c2bbaf --- /dev/null +++ b/src/types/documentId.ts @@ -0,0 +1,18 @@ +import { createUuidv4 } from '@/utils/uuid' + +/** + * Stable frontend-owned identity of a `GraphDocument` (ADR-0024). Every + * document has one, including local and unsaved workflows. A cloud-backed + * document may additionally map a canonical `workflow_id` — the wire address + * used by agent commands — but that mapping lives in the document registry; + * it is never the document's own identity. + */ +export type DocumentId = string & { readonly __brand: 'DocumentId' } + +export function toDocumentId(value: string): DocumentId { + return value as DocumentId +} + +export function createDocumentId(): DocumentId { + return createUuidv4() as DocumentId +} diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 1affee303d4..ca7baaea1d9 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -49,6 +49,7 @@ import { api } from '@/scripts/api' import { app } from '@/scripts/app' import { useAgentNodeSelectionStore } from '@/stores/agentNodeSelectionStore' import { useExecutionErrorStore } from '@/stores/executionErrorStore' +import { useGraphDocumentStore } from '@/stores/graphDocumentStore' import { useWorkflowTabActivityStore } from '@/stores/workflowTabActivityStore' import { useSidebarTabStore } from '@/stores/workspace/sidebarTabStore' import { isLGraphNode } from '@/utils/litegraphUtil' @@ -161,6 +162,7 @@ const tabActivity = useWorkflowTabActivityStore() const CREATING_TAB_MIN_DURATION_MS = 500 const canvasStore = useCanvasStore() +const graphDocumentStore = useGraphDocumentStore() const graphMutationsByWorkflow = new Map< string, ReturnType @@ -168,15 +170,30 @@ const graphMutationsByWorkflow = new Map< const graphMutations = (workflowId: string) => { const existing = graphMutationsByWorkflow.get(workflowId) if (existing) return existing + // Document identity is early-bound (ADR-0024): the registry entry is + // created when the target is first addressed, not at commit time. Commit + // scope resolution then records/refreshes the entry's scope, so a target + // whose tab is momentarily unresolved still commits into its own document. + const documentId = + graphDocumentStore.resolveWorkflowTarget(workflowId)?.documentId ?? + graphDocumentStore.createDocument({ workflowId }) const mutations = createGraphMutations({ getScope() { - const rootGraphId = boundTabFor(workflowId)?.activeState?.id - return rootGraphId - ? { - rootGraphId: toRootGraphId(rootGraphId), - owningGraphId: toOwningGraphId(rootGraphId) - } + const registered = documentId + ? (graphDocumentStore.getDocument(documentId)?.scope ?? null) : null + const rootGraphId = boundTabFor(workflowId)?.activeState?.id + if (!rootGraphId) return registered + const scope = { + rootGraphId: toRootGraphId(rootGraphId), + owningGraphId: toOwningGraphId(rootGraphId) + } + if (documentId) { + if (!registered) graphDocumentStore.hydrateDocument(documentId, scope) + else if (registered.rootGraphId !== scope.rootGraphId) + graphDocumentStore.rebindScope(documentId, scope) + } + return scope }, layout: { createNode(scope, nodeId, layout, context) { diff --git a/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts b/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts new file mode 100644 index 00000000000..c0f8456197b --- /dev/null +++ b/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts @@ -0,0 +1,364 @@ +import { + appliedOpIds, + mint, + NODE_INCARNATION_KEY, + nodesMap, + readStamps +} from '@comfyorg/comfy-multi-player' +import type { WidgetCatalog } from '@comfyorg/comfy-multi-player' +import { createTestingPinia } from '@pinia/testing' +import { setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import * as Y from 'yjs' + +import { createActivationCoordinator } from '@/core/graph/document/activationCoordinator' +import type { DocumentViewBinding } from '@/core/graph/document/activationCoordinator' +import { createDetachedTargetSession } from '@/core/graph/document/detachedTargetSession' +import type { DetachedTargetSession } from '@/core/graph/document/detachedTargetSession' +import { serializeDocumentScope } from '@/core/graph/document/documentSerializer' +import { createGraphMutations } from '@/core/graph/graphMutations' +import type { GraphMutations } from '@/core/graph/graphMutations' +import { useGraphDocumentStore } from '@/stores/graphDocumentStore' +import type { DocumentId } from '@/types/documentId' +import type { GraphScope } from '@/types/graphScopeId' +import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' + +import { createTargetFrameApplyPort } from './targetFrameProjection' + +const catalog: WidgetCatalog = { + types: { + Source: { widget_order: ['seed', 'stale'] }, + Sink: { widget_order: [] } + } +} + +const workflowJson = { + nodes: [ + { + id: 1, + type: 'Source', + title: 'Producer', + pos: [10, 20], + size: [180, 90], + inputs: [], + outputs: [{ name: 'out', type: 'IMAGE', links: [9] }], + widgets_values: { seed: 42, stale: 7 } + }, + { + id: 2, + type: 'Sink', + pos: [300, 20], + inputs: [{ name: 'in', type: 'IMAGE', link: 9 }], + outputs: [] + } + ], + links: [[9, 1, 0, 2, 0, 'IMAGE']] as [ + number, + number, + number, + number, + number, + string + ][] +} + +function scopeFor(graphId: string): GraphScope { + return { + rootGraphId: toRootGraphId(graphId), + owningGraphId: toOwningGraphId(graphId) + } +} + +function mutationsFor(scope: GraphScope): GraphMutations { + return createGraphMutations({ + getScope: () => scope, + layout: { createNode: vi.fn(), deleteNodes: vi.fn() } + }) +} + +function commitHostState( + session: DetachedTargetSession, + workflowId: string, + host: Y.Doc, + mutations: GraphMutations, + seq = 1 +): void { + expect( + session.enqueue({ + workflowId, + seq, + update: Y.encodeStateAsUpdate(host), + actor: 'agent:test', + opIds: [`bootstrap-${seq}`] + }).status + ).toBe('queued') + expect(session.commitNext(createTargetFrameApplyPort(mutations)).status).toBe( + 'committed' + ) +} + +/** A fake renderer-mode binding: activation must never touch semantic state. */ +function modeBinding(log: string[], mode: string): DocumentViewBinding { + return { + attach: () => log.push(`attach:${mode}`), + detach: () => log.push(`detach:${mode}`) + } +} + +function registerLoadedDocument(workflowId: string, scope: GraphScope) { + const registry = useGraphDocumentStore() + const documentId = registry.createDocument({ workflowId }) + if (documentId === null) throw new Error('duplicate workflow mapping') + expect(registry.hydrateDocument(documentId, scope)).toBe(true) + return { registry, documentId } +} + +function loadedCoordinator() { + const registry = useGraphDocumentStore() + return createActivationCoordinator({ + isLoaded: (id: DocumentId) => + registry.getDocument(id)?.state.phase === 'loaded' + }) +} + +describe('document activation persistence (ADR-0024 seam)', () => { + beforeEach(() => { + setActivePinia(createTestingPinia({ stubActions: false })) + }) + + it('serializes byte-identically across Base/ECS/Nodes-2.0 activation cycles and save/reload', async () => { + const scope = scopeFor('root') + const mutations = mutationsFor(scope) + const host = mint(workflowJson, catalog) + const session = createDetachedTargetSession('wf') + commitHostState(session, 'wf', host, mutations) + + const baseline = serializeDocumentScope(scope) + expect(baseline.length).toBeGreaterThan(2) + + const { registry, documentId } = registerLoadedDocument('wf', scope) + const coordinator = loadedCoordinator() + const log: string[] = [] + + for (const mode of ['base', 'ecs', 'nodes2']) { + const outcome = await coordinator.activate( + documentId, + modeBinding(log, mode) + ) + expect(outcome.status).toBe('activated') + expect(serializeDocumentScope(scope)).toEqual(baseline) + expect(coordinator.deactivate(documentId)).toBe(true) + expect(serializeDocumentScope(scope)).toEqual(baseline) + } + expect(log).toEqual([ + 'attach:base', + 'detach:base', + 'attach:ecs', + 'detach:ecs', + 'attach:nodes2', + 'detach:nodes2' + ]) + + const ticket = registry.beginSave(documentId) + expect(ticket).not.toBeNull() + const savedBytes = serializeDocumentScope(scope) + expect(registry.completeSave(ticket!)).toBe(true) + expect(registry.persistenceStateOf(documentId)).toBe('clean') + + const reloadSession = createDetachedTargetSession('wf') + reloadSession.enqueue({ + workflowId: 'wf', + seq: 1, + update: session.encodeCommittedState() + }) + expect( + reloadSession.commitNext(createTargetFrameApplyPort(mutations)).status + ).toBe('committed') + + expect(serializeDocumentScope(scope)).toEqual(savedBytes) + expect(serializeDocumentScope(scope)).toEqual(baseline) + + session.destroy() + reloadSession.destroy() + host.destroy() + }) + + it('reloads byte-identically while a different renderer mode is active', async () => { + const scope = scopeFor('root') + const mutations = mutationsFor(scope) + const host = mint(workflowJson, catalog) + const session = createDetachedTargetSession('wf') + commitHostState(session, 'wf', host, mutations) + const baseline = serializeDocumentScope(scope) + + const otherScope = scopeFor('other-root') + const { documentId: otherDocumentId } = registerLoadedDocument( + 'wf-other', + otherScope + ) + const coordinator = loadedCoordinator() + await coordinator.activate(otherDocumentId, modeBinding([], 'nodes2')) + + const reloadSession = createDetachedTargetSession('wf') + reloadSession.enqueue({ + workflowId: 'wf', + seq: 1, + update: session.encodeCommittedState() + }) + expect( + reloadSession.commitNext(createTargetFrameApplyPort(mutations)).status + ).toBe('committed') + + expect(serializeDocumentScope(scope)).toEqual(baseline) + expect(coordinator.activeDocumentId()).toBe(otherDocumentId) + + session.destroy() + reloadSession.destroy() + host.destroy() + }) + + it('preserves original stamps and DQ-11(c) node incarnations through the staged commit path', () => { + const scope = scopeFor('root') + const mutations = mutationsFor(scope) + const host = mint(workflowJson, catalog) + const session = createDetachedTargetSession('wf') + commitHostState(session, 'wf', host, mutations) + + const committed = new Y.Doc() + Y.applyUpdate(committed, session.encodeCommittedState()) + + expect(readStamps(committed)).toEqual(readStamps(host)) + expect([...appliedOpIds(committed)].sort()).toEqual( + [...appliedOpIds(host)].sort() + ) + for (const id of ['1', '2']) { + const hostIncarnation = nodesMap(host).get(id)?.get(NODE_INCARNATION_KEY) + expect(typeof hostIncarnation).toBe('string') + expect(nodesMap(committed).get(id)?.get(NODE_INCARNATION_KEY)).toBe( + hostIncarnation + ) + } + + committed.destroy() + session.destroy() + host.destroy() + }) + + it('isolates agent frames from the active canvas: frames land in their registry-resolved scope only', async () => { + const scopeA = scopeFor('root-a') + const scopeB = scopeFor('root-b') + const mutationsA = mutationsFor(scopeA) + const mutationsB = mutationsFor(scopeB) + + const hostA = mint(workflowJson, catalog) + const sessionA = createDetachedTargetSession('wf-a') + commitHostState(sessionA, 'wf-a', hostA, mutationsA) + const bytesA = serializeDocumentScope(scopeA) + + const registryA = registerLoadedDocument('wf-a', scopeA) + const registryB = registerLoadedDocument('wf-b', scopeB) + const registry = useGraphDocumentStore() + + const coordinator = loadedCoordinator() + await coordinator.activate(registryA.documentId, modeBinding([], 'base')) + + const target = registry.resolveWorkflowTarget('wf-b') + expect(target?.documentId).toBe(registryB.documentId) + expect(target?.scope).toEqual(scopeB) + expect(target?.documentId).not.toBe(coordinator.activeDocumentId()) + + const hostB = mint({ nodes: [workflowJson.nodes[1]!], links: [] }, catalog) + const sessionB = createDetachedTargetSession('wf-b') + commitHostState(sessionB, 'wf-b', hostB, mutationsB) + + expect(serializeDocumentScope(scopeA)).toEqual(bytesA) + expect(serializeDocumentScope(scopeB)).not.toEqual(bytesA) + + sessionA.destroy() + sessionB.destroy() + hostA.destroy() + hostB.destroy() + }) + + it('recovers a detached target across reconnect via the last committed state vector', () => { + const scope = scopeFor('root') + const mutations = mutationsFor(scope) + const host = mint(workflowJson, catalog) + const session = createDetachedTargetSession('wf') + commitHostState(session, 'wf', host, mutations) + const baseline = serializeDocumentScope(scope) + + const beforeMissed = Y.encodeStateVector(host) + nodesMap(host).get('1')?.set('title', 'Renamed while offline') + const missedFrame = { + workflowId: 'wf', + seq: 2, + update: Y.encodeStateAsUpdate(host, beforeMissed) + } + nodesMap(host).get('1')?.set('color', '#123456') + + expect(session.enqueue(missedFrame).status).toBe('queued') + const gap = session.enqueue({ + workflowId: 'wf', + seq: 4, + update: Y.encodeStateAsUpdate(host, Y.encodeStateVector(host)) + }) + expect(gap.status).toBe('gap') + expect(serializeDocumentScope(scope)).toEqual(baseline) + + session.beginResync() + session.enqueue({ + workflowId: 'wf', + seq: 4, + update: Y.encodeStateAsUpdate(host, session.recoveryStateVector()) + }) + expect( + session.commitNext(createTargetFrameApplyPort(mutations)).status + ).toBe('committed') + + const committed = new Y.Doc() + Y.applyUpdate(committed, session.encodeCommittedState()) + expect(nodesMap(committed).toJSON()).toEqual(nodesMap(host).toJSON()) + committed.destroy() + + expect(serializeDocumentScope(scope)).not.toEqual(baseline) + + session.destroy() + host.destroy() + }) + + it('doc_reset starts a new lineage whose fresh mint replaces the scope content', () => { + const scope = scopeFor('root') + const mutations = mutationsFor(scope) + const host = mint(workflowJson, catalog) + const session = createDetachedTargetSession('wf') + commitHostState(session, 'wf', host, mutations) + const oldLineage = session.snapshot().lineage + + session.resetLineage(10) + expect(session.snapshot().lineage).not.toBe(oldLineage) + + const remintedHost = mint( + { nodes: [workflowJson.nodes[0]!], links: [] }, + catalog + ) + commitHostState(session, 'wf', remintedHost, mutations, 11) + + const committed = new Y.Doc() + Y.applyUpdate(committed, session.encodeCommittedState()) + expect([...nodesMap(committed).keys()]).toEqual(['1']) + committed.destroy() + + const reloaded = serializeDocumentScope(scope) + const parsed = JSON.parse(new TextDecoder().decode(reloaded)) as { + nodes: { id: string }[] + links: unknown[] + } + expect(parsed.nodes.map(({ id }) => id)).toEqual(['1']) + expect(parsed.links).toEqual([]) + + session.destroy() + host.destroy() + remintedHost.destroy() + }) +}) diff --git a/src/workbench/extensions/agent/crdt/targetFrameProjection.ts b/src/workbench/extensions/agent/crdt/targetFrameProjection.ts new file mode 100644 index 00000000000..c9b35142253 --- /dev/null +++ b/src/workbench/extensions/agent/crdt/targetFrameProjection.ts @@ -0,0 +1,139 @@ +import { + linksMap, + nodesMap, + OPAQUE_WIDGETS_KEY +} from '@comfyorg/comfy-multi-player' +import * as Y from 'yjs' + +import type { + TargetFrame, + TargetFrameApplyPort +} from '@/core/graph/document/detachedTargetSession' +import type { + GraphMutations, + SemanticLinkPayload, + SemanticNodePayload +} from '@/core/graph/graphMutations' +import type { RemoteMutationContext } from '@/types/graphMutationContext' +import { compareNodeIds, toNodeId } from '@/types/nodeId' + +function plain(value: unknown): unknown { + if (value instanceof Y.Map || value instanceof Y.Array) return value.toJSON() + return structuredClone(value) +} + +/** + * Staged-doc counterpart of the adapter's live readers: the adapter reads + * incremental observer effects off its bound follower doc, while this reads + * whole snapshots off a detached session's staged doc. Kept local because the + * projection must never depend on adapter internals (ADR-0024's seam). + */ +function readSemanticNode(doc: Y.Doc, id: string): SemanticNodePayload | null { + const source = nodesMap(doc).get(id) + if (!(source instanceof Y.Map)) return null + const type = source.get('type') + if (typeof type !== 'string' || type.length === 0) return null + + const payload: Record = {} + source.forEach((value, key) => { + if (key === 'widgets' && value instanceof Y.Map) { + payload.widgets_values = value.toJSON() + } else if (key === OPAQUE_WIDGETS_KEY) { + payload.widgets_values = plain(value) + } else { + payload[key] = plain(value) + } + }) + payload.id = id + payload.type = type + return payload as SemanticNodePayload +} + +function readNodeSlots( + doc: Y.Doc, + id: string, + key: TKey +): SemanticLinkPayload[TKey extends 'inputs' + ? 'targetInputs' + : 'originOutputs'] { + const value = nodesMap(doc).get(id)?.get(key) + return ( + value instanceof Y.Array ? value.toJSON() : [] + ) as SemanticLinkPayload[TKey extends 'inputs' + ? 'targetInputs' + : 'originOutputs'] +} + +function readSemanticLink(doc: Y.Doc, id: string): SemanticLinkPayload | null { + const raw = linksMap(doc).get(id) + const tuple = raw instanceof Y.Array ? raw.toArray() : raw + if (!Array.isArray(tuple) || tuple.length < 5) return null + const linkId = Number(tuple[0] ?? id) + const originSlot = Number(tuple[2]) + const targetSlot = Number(tuple[4]) + if ( + !Number.isInteger(linkId) || + tuple[1] == null || + tuple[3] == null || + !Number.isInteger(originSlot) || + !Number.isInteger(targetSlot) + ) { + return null + } + return { + id: linkId, + originNodeId: String(tuple[1]), + originSlot, + targetNodeId: String(tuple[3]), + targetSlot, + type: + typeof tuple[5] === 'string' || typeof tuple[5] === 'number' + ? tuple[5] + : '*', + originOutputs: readNodeSlots(doc, String(tuple[1]), 'outputs'), + targetInputs: readNodeSlots(doc, String(tuple[3]), 'inputs') + } +} + +function frameContext(frame: TargetFrame): RemoteMutationContext { + const opIds = frame.opIds?.filter((id) => id.length > 0) + return { + source: 'agent-remote', + actor: frame.actor ?? 'agent-replay', + opId: opIds?.at(-1) ?? 'replay', + ...(opIds && opIds.length > 0 && { opIds: [...opIds] }) + } +} + +/** + * Full-snapshot projection of a detached target session's staged document + * into the ECS stores through the target's `GraphMutations` composite. One + * atomic batch clears the scope and rebuilds it from the staged doc, so a + * validation failure anywhere leaves the stores untouched and the frame + * queued (the session's all-or-nothing commit contract). + */ +export function createTargetFrameApplyPort( + mutations: GraphMutations +): TargetFrameApplyPort { + return { + apply(frame, stagedDoc) { + const nodeIds = [...nodesMap(stagedDoc).keys()].sort((left, right) => + compareNodeIds(toNodeId(left), toNodeId(right)) + ) + const linkIds = [...linksMap(stagedDoc).keys()].sort( + (left, right) => Number(left) - Number(right) + ) + return mutations.batch(frameContext(frame), (batch) => { + batch.clearSemanticGraph() + for (const id of nodeIds) { + const payload = readSemanticNode(stagedDoc, id) + if (payload) batch.reconcileNode(payload) + } + for (const id of linkIds) { + const link = readSemanticLink(stagedDoc, id) + if (link) batch.connect(link) + } + }) + } + } +} From a1b86dec8d5fb740d3bfb9fb202da480e5d2861c Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 05:02:54 +0000 Subject: [PATCH 02/37] fix(agent): treat malformed frame bytes as a failed commit, not a throw Move the staged-doc build (encodeStateAsUpdate + applyUpdate) inside the try block in commitNext so corrupt update bytes surface as {status: 'failed', seq, error} and the staged doc is destroyed, matching the documented CommitResult contract. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3897084733 --- .../document/detachedTargetSession.test.ts | 19 +++++++++++++++++++ .../graph/document/detachedTargetSession.ts | 5 ++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/core/graph/document/detachedTargetSession.test.ts b/src/core/graph/document/detachedTargetSession.test.ts index d3f3d2e0e38..a65afe5b0c2 100644 --- a/src/core/graph/document/detachedTargetSession.test.ts +++ b/src/core/graph/document/detachedTargetSession.test.ts @@ -171,6 +171,25 @@ describe('createDetachedTargetSession', () => { expect(session.snapshot().committedSeq).toBeNull() }) + it('a frame with malformed update bytes reports failed instead of throwing', () => { + const session = createDetachedTargetSession(WORKFLOW_ID) + session.enqueue({ + workflowId: WORKFLOW_ID, + seq: 1, + update: new Uint8Array([0xff, 0x00, 0x13, 0x37]) + }) + + const result = session.commitNext(acceptAll) + + expect(result.status).toBe('failed') + if (result.status === 'failed') { + expect(result.seq).toBe(1) + expect(result.error).toBeDefined() + } + expect(session.snapshot().queuedFrames).toBe(1) + expect(session.snapshot().committedSeq).toBeNull() + }) + it('skips duplicate frames at or below the last accepted sequence', () => { const source = createFrameSource() const session = createDetachedTargetSession(WORKFLOW_ID) diff --git a/src/core/graph/document/detachedTargetSession.ts b/src/core/graph/document/detachedTargetSession.ts index d0f24176bcc..75be5ce5281 100644 --- a/src/core/graph/document/detachedTargetSession.ts +++ b/src/core/graph/document/detachedTargetSession.ts @@ -133,11 +133,10 @@ export function createDetachedTargetSession( if (!frame) return { status: 'idle' } const staged = new Y.Doc() - Y.applyUpdate(staged, Y.encodeStateAsUpdate(committedDoc)) - Y.applyUpdate(staged, frame.update) - let applied: boolean try { + Y.applyUpdate(staged, Y.encodeStateAsUpdate(committedDoc)) + Y.applyUpdate(staged, frame.update) applied = port.apply(frame, staged) } catch (error) { staged.destroy() From e8846fc0ec1615ec2ae398f41b3b663513495f67 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 05:12:57 +0000 Subject: [PATCH 03/37] fix(agent): reject inherited sequences in isCommitted after lineage reset Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3897084789 --- .../document/detachedTargetSession.test.ts | 24 +++++++++++++++++++ .../graph/document/detachedTargetSession.ts | 11 ++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/core/graph/document/detachedTargetSession.test.ts b/src/core/graph/document/detachedTargetSession.test.ts index a65afe5b0c2..72c0dbc9656 100644 --- a/src/core/graph/document/detachedTargetSession.test.ts +++ b/src/core/graph/document/detachedTargetSession.test.ts @@ -322,6 +322,30 @@ describe('createDetachedTargetSession', () => { freshHost.destroy() }) + it('rejects inherited sequences in isCommitted after a lineage reset', () => { + const session = createDetachedTargetSession(WORKFLOW_ID) + + session.resetLineage(10) + const { lineage } = session.snapshot() + + // Seqs at or below the reset floor were never committed in this lineage. + expect(session.isCommitted(`${lineage}:10`)).toBe(false) + expect(session.isCommitted(`${lineage}:5`)).toBe(false) + + const freshHost = new Y.Doc() + setNode(freshHost, '7', { type: 'Fresh' }) + session.enqueue({ + workflowId: WORKFLOW_ID, + seq: 11, + update: Y.encodeStateAsUpdate(freshHost) + }) + expect(session.commitNext(acceptAll).status).toBe('committed') + + expect(session.isCommitted(`${lineage}:11`)).toBe(true) + expect(session.isCommitted(`${lineage}:10`)).toBe(false) + freshHost.destroy() + }) + it('rejects frames addressed to another target loudly', () => { const session = createDetachedTargetSession(WORKFLOW_ID) const stranger = createFrameSource('wf-other') diff --git a/src/core/graph/document/detachedTargetSession.ts b/src/core/graph/document/detachedTargetSession.ts index 75be5ce5281..b7fd49e110e 100644 --- a/src/core/graph/document/detachedTargetSession.ts +++ b/src/core/graph/document/detachedTargetSession.ts @@ -84,6 +84,11 @@ export function createDetachedTargetSession( let lineage = options.initialLineage ?? createUuidv4() let committedDoc = new Y.Doc() let committedSeq: number | null = null + /** + * Sequences at or below this floor were inherited from a lineage reset, + * not committed through this session; `isCommitted` must reject them. + */ + let committedSeqFloor = 0 let revision = 0 let lastCommitId: string | null = null let needsResync = false @@ -201,6 +206,7 @@ export function createDetachedTargetSession( committedDoc = new Y.Doc() lineage = createUuidv4() committedSeq = atSeq + committedSeqFloor = atSeq expectedSeq = null lastCommitId = null needsResync = false @@ -214,7 +220,10 @@ export function createDetachedTargetSession( const seq = Number(commitId.slice(separator + 1)) if (!Number.isInteger(seq)) return false return ( - commitLineage === lineage && committedSeq !== null && seq <= committedSeq + commitLineage === lineage && + committedSeq !== null && + seq <= committedSeq && + seq > committedSeqFloor ) } From c43525de43cf52527177810aef59fbf88bd56c69 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 05:28:00 +0000 Subject: [PATCH 04/37] fix(agent): serialize slots via explicit allowlist to exclude runtime state Slot objects carry runtime-only fields (_widget back-references, _data, hasErrors, boundingRect, deprecated link/links getters) that must never reach the canonical serializer: they are nondeterministic across renderers and _widget is cyclic. Project inputs/outputs through an explicit pickSlot allowlist and add a canonicalization depth guard as a safety net against cyclic runtime objects leaking into semantic state. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3897084745 --- .../graph/document/documentSerializer.test.ts | 157 ++++++++++++++++++ src/core/graph/document/documentSerializer.ts | 59 ++++++- 2 files changed, 212 insertions(+), 4 deletions(-) create mode 100644 src/core/graph/document/documentSerializer.test.ts diff --git a/src/core/graph/document/documentSerializer.test.ts b/src/core/graph/document/documentSerializer.test.ts new file mode 100644 index 00000000000..f511bc5d9a7 --- /dev/null +++ b/src/core/graph/document/documentSerializer.test.ts @@ -0,0 +1,157 @@ +import { createTestingPinia } from '@pinia/testing' +import { setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it } from 'vitest' + +import { serializeDocumentScope } from '@/core/graph/document/documentSerializer' +import type { + INodeInputSlot, + INodeOutputSlot +} from '@/lib/litegraph/src/interfaces' +import { useLinkStore } from '@/stores/linkStore' +import { useNodeDataStore } from '@/stores/nodeDataStore' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import type { GraphScope } from '@/types/graphScopeId' +import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' +import { toLinkId } from '@/types/linkId' +import { toNodeId } from '@/types/nodeId' +import type { NodeState } from '@/types/nodeState' +import { widgetId } from '@/types/widgetId' +import { createNodeState } from '@/utils/__tests__/litegraphTestUtils' + +function scopeFor(graphId: string): GraphScope { + return { + rootGraphId: toRootGraphId(graphId), + owningGraphId: toOwningGraphId(graphId) + } +} + +function inputSlot(overrides: Partial = {}): INodeInputSlot { + return { name: 'in', type: 'INT', ...overrides } as INodeInputSlot +} + +function outputSlot(overrides: Partial = {}): INodeOutputSlot { + return { name: 'out', type: 'INT', ...overrides } as INodeOutputSlot +} + +function decode(bytes: Uint8Array): { + nodes: Array< + Record & { + inputs: Record[] + outputs: Record[] + widgets: Record[] + } + > + links: Record[] +} { + return JSON.parse(new TextDecoder().decode(bytes)) +} + +/** Registers one node (with slots), one widget, and one link in `graphId`. */ +function populateScope( + graphId: string, + slots: { input: INodeInputSlot; output: INodeOutputSlot } +): GraphScope { + const scope = scopeFor(graphId) + useNodeDataStore().registerNode( + scope, + createNodeState({ + id: toNodeId(1), + inputs: [slots.input], + outputs: [slots.output] + }) + ) + useWidgetValueStore().registerWidget( + widgetId(scope.rootGraphId, toNodeId(1), 'alpha'), + { type: 'number', value: 3, options: {} } + ) + useLinkStore().registerLink(scope, { + id: toLinkId(9), + graphId: scope.owningGraphId, + originNodeId: toNodeId(1), + originSlot: 0, + targetNodeId: toNodeId(2), + targetSlot: 0, + type: 'INT' + }) + return scope +} + +describe('serializeDocumentScope', () => { + beforeEach(() => { + setActivePinia(createTestingPinia({ stubActions: false })) + }) + + it('serializes only allowlisted slot fields, ignoring runtime-only state', () => { + // Runtime-only junk, including a cycle through `_widget` — the exact + // shape that would explode JSON.stringify if slots were spread as-is. + const cyclicWidget: Record = { name: 'w' } + cyclicWidget.self = cyclicWidget + const scope = populateScope('root-junk', { + input: inputSlot({ + link: toLinkId(5), + _widget: cyclicWidget as never, + hasErrors: true, + boundingRect: [0, 0, 10, 10] + } as Partial), + output: outputSlot({ + links: [toLinkId(5)], + _data: { transient: true }, + slot_index: 0 + } as Partial) + }) + + const decoded = decode(serializeDocumentScope(scope)) + + expect(decoded.nodes).toHaveLength(1) + const [node] = decoded.nodes + expect(node.inputs[0]).toEqual({ name: 'in', type: 'INT' }) + expect(node.outputs[0]).toEqual({ name: 'out', type: 'INT', slot_index: 0 }) + expect(node.widgets).toEqual([{ name: 'alpha', type: 'number', value: 3 }]) + expect(decoded.links).toEqual([ + { + id: 9, + originNodeId: '1', + originSlot: 0, + targetNodeId: '2', + targetSlot: 0, + type: 'INT' + } + ]) + }) + + it('produces byte-identical output for identical semantic content regardless of runtime slot state', () => { + const clean = populateScope('root-clean', { + input: inputSlot(), + output: outputSlot() + }) + const dirty = populateScope('root-dirty', { + input: inputSlot({ + link: toLinkId(7), + hasErrors: true + } as Partial), + output: outputSlot({ + links: [toLinkId(7)], + _data: 'runtime' + } as Partial) + }) + + expect(serializeDocumentScope(clean)).toEqual(serializeDocumentScope(dirty)) + }) + + it('throws on pathologically deep semantic state instead of hanging', () => { + const scope = scopeFor('root-deep') + let deep: unknown = 0 + for (let i = 0; i < 40; i++) deep = [deep] + useNodeDataStore().registerNode( + scope, + createNodeState({ + id: toNodeId(1), + properties: { deep: deep as NodeState['properties'][string] } + }) + ) + + expect(() => serializeDocumentScope(scope)).toThrow( + /max canonicalization depth/ + ) + }) +}) diff --git a/src/core/graph/document/documentSerializer.ts b/src/core/graph/document/documentSerializer.ts index 36992dd3ab8..3ab10ae9136 100644 --- a/src/core/graph/document/documentSerializer.ts +++ b/src/core/graph/document/documentSerializer.ts @@ -1,3 +1,7 @@ +import type { + INodeInputSlot, + INodeOutputSlot +} from '@/lib/litegraph/src/interfaces' import { useLinkStore } from '@/stores/linkStore' import { useNodeDataStore } from '@/stores/nodeDataStore' import { useWidgetValueStore } from '@/stores/widgetValueStore' @@ -6,16 +10,29 @@ import { compareNodeIds } from '@/types/nodeId' const RENDER_ONLY_KEYS = new Set(['boundingRect']) -function canonicalize(value: unknown): unknown { - if (Array.isArray(value)) return value.map(canonicalize) +/** + * Safety net against unbounded or cyclic structures reaching the + * serializer (e.g. runtime objects leaking into semantic state). Semantic + * graph payloads are shallow; anything deeper indicates a bug upstream. + */ +const MAX_CANONICALIZE_DEPTH = 32 + +function canonicalize(value: unknown, depth = 0): unknown { + if (depth > MAX_CANONICALIZE_DEPTH) { + throw new Error( + `serializeDocumentScope: exceeded max canonicalization depth of ${MAX_CANONICALIZE_DEPTH}; semantic state likely contains a cycle or runtime-only object` + ) + } + if (Array.isArray(value)) + return value.map((entry) => canonicalize(entry, depth + 1)) if (value instanceof Map || value instanceof Set) - return canonicalize([...value]) + return canonicalize([...value], depth + 1) if (typeof value === 'object' && value !== null) { const source = value as Record const result: Record = {} for (const key of Object.keys(source).sort()) { if (RENDER_ONLY_KEYS.has(key)) continue - const entry = canonicalize(source[key]) + const entry = canonicalize(source[key], depth + 1) if (entry !== undefined) result[key] = entry } return result @@ -23,6 +40,38 @@ function canonicalize(value: unknown): unknown { return value } +/** + * Explicit allowlist projection of a node slot to its semantic fields. + * Slot objects carry runtime-only state that must never reach the + * serializer: `_widget` (cyclic — widgets reference their node), `_data`, + * `hasErrors`, `boundingRect`, and the deprecated link-store-derived + * `link`/`links` getters. + */ +function pickSlot(slot: INodeInputSlot | INodeOutputSlot) { + const input = slot as Partial + const output = slot as Partial + return { + name: slot.name, + localized_name: slot.localized_name, + label: slot.label, + type: slot.type, + dir: slot.dir, + removable: slot.removable, + shape: slot.shape, + color_off: slot.color_off, + color_on: slot.color_on, + locked: slot.locked, + nameLocked: slot.nameLocked, + pos: slot.pos, + widget: input.widget + ? { name: input.widget.name, type: input.widget.type } + : undefined, + widgetId: input.widgetId, + alwaysVisible: input.alwaysVisible, + slot_index: output.slot_index + } +} + /** * Renderer-independent canonical serialization of one document scope's * semantic ECS state (ADR-0024's persistence seam). Reads only the domain @@ -43,6 +92,8 @@ export function serializeDocumentScope(scope: GraphScope): Uint8Array { .sort((left, right) => compareNodeIds(left.id, right.id)) .map(({ graphId: _graphId, lastSerialization: _cache, ...semantic }) => ({ ...semantic, + inputs: semantic.inputs.map(pickSlot), + outputs: semantic.outputs.map(pickSlot), widgets: widgetStore .getNodeWidgets(scope.rootGraphId, semantic.id) .map(({ name, type, value }) => ({ name, type, value })) From 7ed7c0b223ece32aee7f8ea8d25b7ac7f4c89695 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 05:30:43 +0000 Subject: [PATCH 05/37] fix(agent): sort widgets by code unit for locale-independent canonical bytes Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3897084823 --- .../graph/document/documentSerializer.test.ts | 25 +++++++++++++++++++ src/core/graph/document/documentSerializer.ts | 6 ++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/core/graph/document/documentSerializer.test.ts b/src/core/graph/document/documentSerializer.test.ts index f511bc5d9a7..5bf7f4eec92 100644 --- a/src/core/graph/document/documentSerializer.test.ts +++ b/src/core/graph/document/documentSerializer.test.ts @@ -138,6 +138,31 @@ describe('serializeDocumentScope', () => { expect(serializeDocumentScope(clean)).toEqual(serializeDocumentScope(dirty)) }) + it('sorts widgets by code unit, independent of host locale', () => { + const scope = scopeFor('root-widget-sort') + useNodeDataStore().registerNode(scope, createNodeState({ id: toNodeId(1) })) + const widgetStore = useWidgetValueStore() + // Registration order: 'a' first. localeCompare would sort 'a' before 'B'; + // code-unit order puts 'B' (66) before 'a' (97). + widgetStore.registerWidget(widgetId(scope.rootGraphId, toNodeId(1), 'a'), { + type: 'number', + value: 1, + options: {} + }) + widgetStore.registerWidget(widgetId(scope.rootGraphId, toNodeId(1), 'B'), { + type: 'number', + value: 2, + options: {} + }) + + const decoded = decode(serializeDocumentScope(scope)) + + expect(decoded.nodes[0].widgets.map((widget) => widget.name)).toEqual([ + 'B', + 'a' + ]) + }) + it('throws on pathologically deep semantic state instead of hanging', () => { const scope = scopeFor('root-deep') let deep: unknown = 0 diff --git a/src/core/graph/document/documentSerializer.ts b/src/core/graph/document/documentSerializer.ts index 3ab10ae9136..47498018f87 100644 --- a/src/core/graph/document/documentSerializer.ts +++ b/src/core/graph/document/documentSerializer.ts @@ -97,7 +97,11 @@ export function serializeDocumentScope(scope: GraphScope): Uint8Array { widgets: widgetStore .getNodeWidgets(scope.rootGraphId, semantic.id) .map(({ name, type, value }) => ({ name, type, value })) - .sort((left, right) => left.name.localeCompare(right.name)) + // Code-unit comparison, not localeCompare: canonical bytes must not + // depend on the host's locale. + .sort((left, right) => + left.name < right.name ? -1 : left.name > right.name ? 1 : 0 + ) })) const links = [...linkStore.graphTopologies(scope)] From f4f872c94154f4a0e0b67769beab9a21bc168831 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 05:34:40 +0000 Subject: [PATCH 06/37] fix(agent): reject target frames with malformed entries before mutating stores Pre-read and validate every node and link in the staged snapshot before opening the mutations batch. A malformed entry now rejects the frame without clearing or partially rebuilding the semantic graph, making apply all-or-nothing as documented. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3897084755 --- .../agent/crdt/targetFrameProjection.test.ts | 120 ++++++++++++++++++ .../agent/crdt/targetFrameProjection.ts | 27 ++-- 2 files changed, 139 insertions(+), 8 deletions(-) create mode 100644 src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts diff --git a/src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts b/src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts new file mode 100644 index 00000000000..36af26fe654 --- /dev/null +++ b/src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it } from 'vitest' +import * as Y from 'yjs' + +import type { TargetFrame } from '@/core/graph/document/detachedTargetSession' +import type { GraphMutations } from '@/core/graph/graphMutations' +import { createTargetFrameApplyPort } from '@/workbench/extensions/agent/crdt/targetFrameProjection' + +type RecordedCall = + | { kind: 'clearSemanticGraph' } + | { kind: 'reconcileNode'; id: unknown; type: unknown } + | { kind: 'connect'; id: unknown } + +function recordingMutations(): { + mutations: GraphMutations + calls: RecordedCall[] + contexts: unknown[] +} { + const calls: RecordedCall[] = [] + const contexts: unknown[] = [] + const fail = () => { + throw new Error('projection must only use batch()') + } + const mutations: GraphMutations = { + batch(context, define) { + contexts.push(context) + define({ + addNode: fail, + reconcileNode: (payload) => + calls.push({ + kind: 'reconcileNode', + id: payload.id, + type: payload.type + }), + setWidget: fail, + connect: (link) => calls.push({ kind: 'connect', id: link.id }), + removeLinks: fail, + deleteNode: fail, + clearSemanticGraph: () => calls.push({ kind: 'clearSemanticGraph' }) + }) + return true + }, + addNode: fail, + setWidget: fail, + connect: fail, + deleteNode: fail, + clearSemanticGraph: fail + } + return { mutations, calls, contexts } +} + +function setNode(doc: Y.Doc, id: string, fields: Record) { + const nodes = doc.getMap>('nodes') + const node = new Y.Map() + nodes.set(id, node) + for (const [key, value] of Object.entries(fields)) node.set(key, value) +} + +function setLink(doc: Y.Doc, id: string, tuple: unknown[]) { + doc.getMap('links').set(id, tuple) +} + +const frame: TargetFrame = { + workflowId: 'wf-projection', + seq: 1, + update: new Uint8Array(), + actor: 'agent-a', + opIds: ['op-1', 'op-2'] +} + +describe('createTargetFrameApplyPort', () => { + it('projects the staged snapshot as one clear-then-rebuild batch', () => { + const doc = new Y.Doc() + setNode(doc, '2', { type: 'Sink' }) + setNode(doc, '1', { type: 'Source' }) + setLink(doc, '9', [9, '1', 0, '2', 0, 'INT']) + const { mutations, calls, contexts } = recordingMutations() + + const applied = createTargetFrameApplyPort(mutations).apply(frame, doc) + + expect(applied).toBe(true) + expect(calls).toEqual([ + { kind: 'clearSemanticGraph' }, + { kind: 'reconcileNode', id: '1', type: 'Source' }, + { kind: 'reconcileNode', id: '2', type: 'Sink' }, + { kind: 'connect', id: 9 } + ]) + expect(contexts).toEqual([ + { + source: 'agent-remote', + actor: 'agent-a', + opId: 'op-2', + opIds: ['op-1', 'op-2'] + } + ]) + }) + + it('rejects the frame without mutating when a node is malformed', () => { + const doc = new Y.Doc() + setNode(doc, '1', { type: 'Source' }) + setNode(doc, '2', { title: 'missing type' }) + const { mutations, calls } = recordingMutations() + + const applied = createTargetFrameApplyPort(mutations).apply(frame, doc) + + expect(applied).toBe(false) + expect(calls).toEqual([]) + }) + + it('rejects the frame without mutating when a link is malformed', () => { + const doc = new Y.Doc() + setNode(doc, '1', { type: 'Source' }) + setLink(doc, '9', [9, '1', 0]) + const { mutations, calls } = recordingMutations() + + const applied = createTargetFrameApplyPort(mutations).apply(frame, doc) + + expect(applied).toBe(false) + expect(calls).toEqual([]) + }) +}) diff --git a/src/workbench/extensions/agent/crdt/targetFrameProjection.ts b/src/workbench/extensions/agent/crdt/targetFrameProjection.ts index c9b35142253..ca0e52a355c 100644 --- a/src/workbench/extensions/agent/crdt/targetFrameProjection.ts +++ b/src/workbench/extensions/agent/crdt/targetFrameProjection.ts @@ -123,16 +123,27 @@ export function createTargetFrameApplyPort( const linkIds = [...linksMap(stagedDoc).keys()].sort( (left, right) => Number(left) - Number(right) ) + + // Read and validate the whole snapshot before touching the stores: a + // malformed entry rejects the frame outright instead of applying a + // partial graph (the session's all-or-nothing commit contract). + const nodes: SemanticNodePayload[] = [] + for (const id of nodeIds) { + const payload = readSemanticNode(stagedDoc, id) + if (!payload) return false + nodes.push(payload) + } + const links: SemanticLinkPayload[] = [] + for (const id of linkIds) { + const link = readSemanticLink(stagedDoc, id) + if (!link) return false + links.push(link) + } + return mutations.batch(frameContext(frame), (batch) => { batch.clearSemanticGraph() - for (const id of nodeIds) { - const payload = readSemanticNode(stagedDoc, id) - if (payload) batch.reconcileNode(payload) - } - for (const id of linkIds) { - const link = readSemanticLink(stagedDoc, id) - if (link) batch.connect(link) - } + for (const node of nodes) batch.reconcileNode(node) + for (const link of links) batch.connect(link) }) } } From 64af88f1746ecd658da043f2cbe369d0a46968e7 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 05:39:14 +0000 Subject: [PATCH 07/37] fix(agent): make activation handoff exception-safe A throwing detach/attach during the activate handoff previously left the old binding published as active, so the next activate or deactivate would detach the same document a second time, and the caller saw a rejected promise instead of an ActivationOutcome. Clear the published binding before the handoff and report a handoff-failed rejection on throw. Deactivate likewise clears state before detaching. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3897084775 --- .../document/activationCoordinator.test.ts | 53 +++++++++++++++++++ .../graph/document/activationCoordinator.ts | 17 ++++-- 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/src/core/graph/document/activationCoordinator.test.ts b/src/core/graph/document/activationCoordinator.test.ts index 94c9506be5c..deca8ab1ddb 100644 --- a/src/core/graph/document/activationCoordinator.test.ts +++ b/src/core/graph/document/activationCoordinator.test.ts @@ -152,6 +152,59 @@ describe('createActivationCoordinator', () => { expect(log).toEqual([`attach:a:${docA}`, `detach:a:${docA}`]) }) + it('rejects with handoff-failed and clears active when attach throws', async () => { + const coordinator = createActivationCoordinator({ isLoaded: () => true }) + const log: string[] = [] + const docA = toDocumentId('doc-a') + const docB = toDocumentId('doc-b') + await coordinator.activate(docA, recordingBinding(log, 'a')) + + const throwingBinding: DocumentViewBinding = { + attach: () => { + throw new Error('attach boom') + }, + detach: (id) => log.push(`detach:b:${id}`) + } + const outcome = await coordinator.activate(docB, throwingBinding) + + expect(outcome).toEqual({ + status: 'rejected', + documentId: docB, + reason: 'handoff-failed' + }) + expect(coordinator.activeDocumentId()).toBeNull() + // The previous document was detached exactly once before the failure. + expect(log).toEqual([`attach:a:${docA}`, `detach:a:${docA}`]) + }) + + it('does not detach the previous document twice after a throwing detach', async () => { + const coordinator = createActivationCoordinator({ isLoaded: () => true }) + const log: string[] = [] + const docA = toDocumentId('doc-a') + const docB = toDocumentId('doc-b') + const throwingDetach: DocumentViewBinding = { + attach: (id) => log.push(`attach:a:${id}`), + detach: () => { + throw new Error('detach boom') + } + } + await coordinator.activate(docA, throwingDetach) + + const outcome = await coordinator.activate(docB, recordingBinding(log, 'b')) + + expect(outcome).toEqual({ + status: 'rejected', + documentId: docB, + reason: 'handoff-failed' + }) + expect(coordinator.activeDocumentId()).toBeNull() + + // A follow-up activate succeeds without re-detaching the failed binding. + const retry = await coordinator.activate(docB, recordingBinding(log, 'b')) + expect(retry).toEqual({ status: 'activated', documentId: docB }) + expect(log).toEqual([`attach:a:${docA}`, `attach:b:${docB}`]) + }) + it('deactivate of a non-active document is a no-op', async () => { const coordinator = createActivationCoordinator({ isLoaded: () => true }) const log: string[] = [] diff --git a/src/core/graph/document/activationCoordinator.ts b/src/core/graph/document/activationCoordinator.ts index 00f9bf23eff..e06157384c6 100644 --- a/src/core/graph/document/activationCoordinator.ts +++ b/src/core/graph/document/activationCoordinator.ts @@ -18,7 +18,7 @@ export type ActivationOutcome = | { status: 'rejected' documentId: DocumentId - reason: 'not-loaded' | 'hydration-failed' + reason: 'not-loaded' | 'hydration-failed' | 'handoff-failed' } export interface ActivationCoordinatorDeps { @@ -62,8 +62,16 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { if (!deps.isLoaded(documentId)) return { status: 'rejected', documentId, reason: 'not-loaded' } - if (active) active.binding.detach(active.documentId) - binding.attach(documentId) + const previous = active + active = null + try { + if (previous) previous.binding.detach(previous.documentId) + binding.attach(documentId) + } catch { + // A throwing detach/attach must not leave a stale published binding: a + // later activate/deactivate would detach the old document twice. + return { status: 'rejected', documentId, reason: 'handoff-failed' } + } active = { documentId, binding } return { status: 'activated', documentId } } @@ -76,8 +84,9 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { function deactivate(documentId: DocumentId): boolean { if (active?.documentId !== documentId) return false generation++ - active.binding.detach(documentId) + const previous = active active = null + previous.binding.detach(documentId) return true } From ec3285e6feaab6f67ed5a620ceb041165ca8cb0c Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 05:41:01 +0000 Subject: [PATCH 08/37] fix(agent): let deactivate cancel an unpublished in-flight activation deactivate only bumped the generation when the document was already the published active one, so deactivate(B) while activate(B) was still hydrating could not cancel it and the activation completed anyway. Track the in-flight request's document id and advance the generation for any deactivate that targets it. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3897084783 --- .../document/activationCoordinator.test.ts | 18 ++++++++++ .../graph/document/activationCoordinator.ts | 35 ++++++++++++++----- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/core/graph/document/activationCoordinator.test.ts b/src/core/graph/document/activationCoordinator.test.ts index deca8ab1ddb..5e998efa3ff 100644 --- a/src/core/graph/document/activationCoordinator.test.ts +++ b/src/core/graph/document/activationCoordinator.test.ts @@ -152,6 +152,24 @@ describe('createActivationCoordinator', () => { expect(log).toEqual([`attach:a:${docA}`, `detach:a:${docA}`]) }) + it('deactivate cancels an in-flight activate for the same document', async () => { + const slowHydration = deferred() + const docB = toDocumentId('doc-b') + const coordinator = createActivationCoordinator({ + isLoaded: () => true, + hydrate: () => slowHydration.promise + }) + const log: string[] = [] + + const inFlight = coordinator.activate(docB, recordingBinding(log, 'b')) + expect(coordinator.deactivate(docB)).toBe(true) + slowHydration.resolve() + + expect(await inFlight).toEqual({ status: 'superseded', documentId: docB }) + expect(coordinator.activeDocumentId()).toBeNull() + expect(log).toEqual([]) + }) + it('rejects with handoff-failed and clears active when attach throws', async () => { const coordinator = createActivationCoordinator({ isLoaded: () => true }) const log: string[] = [] diff --git a/src/core/graph/document/activationCoordinator.ts b/src/core/graph/document/activationCoordinator.ts index e06157384c6..97ca3b18575 100644 --- a/src/core/graph/document/activationCoordinator.ts +++ b/src/core/graph/document/activationCoordinator.ts @@ -42,6 +42,7 @@ export interface ActivationCoordinatorDeps { */ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { let generation = 0 + let pendingDocumentId: DocumentId | null = null let active: { documentId: DocumentId; binding: DocumentViewBinding } | null = null @@ -50,17 +51,24 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { binding: DocumentViewBinding ): Promise { const requestGeneration = ++generation + pendingDocumentId = documentId const stale = (): boolean => requestGeneration !== generation + const finish = (outcome: ActivationOutcome): ActivationOutcome => { + if (!stale()) pendingDocumentId = null + return outcome + } try { await deps.hydrate?.(documentId) } catch { - return stale() - ? { status: 'superseded', documentId } - : { status: 'rejected', documentId, reason: 'hydration-failed' } + return finish( + stale() + ? { status: 'superseded', documentId } + : { status: 'rejected', documentId, reason: 'hydration-failed' } + ) } - if (stale()) return { status: 'superseded', documentId } + if (stale()) return finish({ status: 'superseded', documentId }) if (!deps.isLoaded(documentId)) - return { status: 'rejected', documentId, reason: 'not-loaded' } + return finish({ status: 'rejected', documentId, reason: 'not-loaded' }) const previous = active active = null @@ -70,10 +78,14 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { } catch { // A throwing detach/attach must not leave a stale published binding: a // later activate/deactivate would detach the old document twice. - return { status: 'rejected', documentId, reason: 'handoff-failed' } + return finish({ + status: 'rejected', + documentId, + reason: 'handoff-failed' + }) } active = { documentId, binding } - return { status: 'activated', documentId } + return finish({ status: 'activated', documentId }) } /** @@ -82,7 +94,14 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { * tracking, and persistence continue to operate. */ function deactivate(documentId: DocumentId): boolean { - if (active?.documentId !== documentId) return false + // Cancel an in-flight activate for this document even when it has not + // been published yet; otherwise the activation would still complete. + const cancelledInFlight = pendingDocumentId === documentId + if (cancelledInFlight) { + generation++ + pendingDocumentId = null + } + if (active?.documentId !== documentId) return cancelledInFlight generation++ const previous = active active = null From a8c9415a229e4be2c7a8c5db54ac5ce67ddee9e1 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 05:44:51 +0000 Subject: [PATCH 09/37] fix(agent): refuse agent writes when the bound tab is unresolved getScope previously fell back to the document's last remembered scope when boundTabFor returned no active tab, which turned a previously safe rejection into a write against a possibly closed tab's ids. Return null so graphMutations refuses the frame instead. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3897084766 --- src/workbench/extensions/agent/AgentPanelRoot.vue | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index ca7baaea1d9..9a8abb0b72e 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -179,11 +179,14 @@ const graphMutations = (workflowId: string) => { graphDocumentStore.createDocument({ workflowId }) const mutations = createGraphMutations({ getScope() { + // No bound tab means no live scope: refuse the write instead of + // replaying it against the last remembered scope (the tab may have + // been closed, and its ids may be reused when the workflow reopens). + const rootGraphId = boundTabFor(workflowId)?.activeState?.id + if (!rootGraphId) return null const registered = documentId ? (graphDocumentStore.getDocument(documentId)?.scope ?? null) : null - const rootGraphId = boundTabFor(workflowId)?.activeState?.id - if (!rootGraphId) return registered const scope = { rootGraphId: toRootGraphId(rootGraphId), owningGraphId: toOwningGraphId(rootGraphId) From 8da1e22655413a991deb4fd6b42f666604f09e69 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 05:46:34 +0000 Subject: [PATCH 10/37] fix(agent): re-resolve document id per commit instead of caching it The graphMutations closure captured documentId once at creation and never invalidated it, so a workflow id remapped to a new document after the previous one closed kept mutating under the dead id, and a transient createDocument rejection cached null permanently. The id is now re-resolved inside getScope on every commit; the eager resolve at closure creation is kept only for its early-binding side effect (ADR-0024). Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3897084799 --- src/workbench/extensions/agent/AgentPanelRoot.vue | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 9a8abb0b72e..85f0cded82e 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -167,6 +167,14 @@ const graphMutationsByWorkflow = new Map< string, ReturnType >() +/** + * Resolve the live document for a workflow id, creating the registry entry + * when none exists. Never captured: a workflow id can be remapped to a new + * document after the previous one closes, so callers re-resolve per use. + */ +const resolveDocumentId = (workflowId: string) => + graphDocumentStore.resolveWorkflowTarget(workflowId)?.documentId ?? + graphDocumentStore.createDocument({ workflowId }) const graphMutations = (workflowId: string) => { const existing = graphMutationsByWorkflow.get(workflowId) if (existing) return existing @@ -174,9 +182,7 @@ const graphMutations = (workflowId: string) => { // created when the target is first addressed, not at commit time. Commit // scope resolution then records/refreshes the entry's scope, so a target // whose tab is momentarily unresolved still commits into its own document. - const documentId = - graphDocumentStore.resolveWorkflowTarget(workflowId)?.documentId ?? - graphDocumentStore.createDocument({ workflowId }) + resolveDocumentId(workflowId) const mutations = createGraphMutations({ getScope() { // No bound tab means no live scope: refuse the write instead of @@ -184,6 +190,7 @@ const graphMutations = (workflowId: string) => { // been closed, and its ids may be reused when the workflow reopens). const rootGraphId = boundTabFor(workflowId)?.activeState?.id if (!rootGraphId) return null + const documentId = resolveDocumentId(workflowId) const registered = documentId ? (graphDocumentStore.getDocument(documentId)?.scope ?? null) : null From 75eafd9f8ba5ff4ca2aa7b4c2f040b9f02e999de Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 05:50:52 +0000 Subject: [PATCH 11/37] fix(agent): advance document revision on successful graph writes Wrap the workflow-scoped GraphMutations composite so every successful write (batch and all single-shot methods) marks the target document mutated. Previously markMutated had no production caller, so document revisions never advanced and revision-based dirty checks could not fire. The document id is re-resolved at success time because a workflow can be rebound to a new document between wrapper creation and the write. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3897084806 --- .../extensions/agent/AgentPanelRoot.vue | 39 ++++++++++++++++--- 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 85f0cded82e..437fe33cc21 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -20,6 +20,7 @@ import { useFocusNode } from '@/composables/canvas/useFocusNode' import { useTelemetry } from '@/platform/telemetry' import { reportError } from '@/platform/telemetry/reportError' import { createGraphMutations } from '@/core/graph/graphMutations' +import type { GraphMutations } from '@/core/graph/graphMutations' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import type { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' @@ -163,10 +164,7 @@ const CREATING_TAB_MIN_DURATION_MS = 500 const canvasStore = useCanvasStore() const graphDocumentStore = useGraphDocumentStore() -const graphMutationsByWorkflow = new Map< - string, - ReturnType ->() +const graphMutationsByWorkflow = new Map() /** * Resolve the live document for a workflow id, creating the registry entry * when none exists. Never captured: a workflow id can be remapped to a new @@ -175,6 +173,34 @@ const graphMutationsByWorkflow = new Map< const resolveDocumentId = (workflowId: string) => graphDocumentStore.resolveWorkflowTarget(workflowId)?.documentId ?? graphDocumentStore.createDocument({ workflowId }) +/** + * Record every successful write against the target's document so its + * revision advances (ADR-0024 dirty tracking). Each method re-resolves the + * document id at success time: the workflow may have been rebound to a new + * document between creation and the write. + */ +const withMutationTracking = ( + inner: GraphMutations, + workflowId: string +): GraphMutations => { + const track = (committed: boolean): boolean => { + if (committed) { + const documentId = resolveDocumentId(workflowId) + if (documentId) graphDocumentStore.markMutated(documentId) + } + return committed + } + return { + batch: (context, define) => track(inner.batch(context, define)), + addNode: (payload, context) => track(inner.addNode(payload, context)), + setWidget: (nodeId, name, value, context) => + track(inner.setWidget(nodeId, name, value, context)), + connect: (link, context) => track(inner.connect(link, context)), + deleteNode: (nodeId, removedLinkIds, context) => + track(inner.deleteNode(nodeId, removedLinkIds, context)), + clearSemanticGraph: (context) => track(inner.clearSemanticGraph(context)) + } +} const graphMutations = (workflowId: string) => { const existing = graphMutationsByWorkflow.get(workflowId) if (existing) return existing @@ -244,8 +270,9 @@ const graphMutations = (workflowId: string) => { } } }) - graphMutationsByWorkflow.set(workflowId, mutations) - return mutations + const tracked = withMutationTracking(mutations, workflowId) + graphMutationsByWorkflow.set(workflowId, tracked) + return tracked } const { focusNodeInstance } = useFocusNode() From dfff06cd49ccb8b46476ffe38af452dd94edd538 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 06:16:10 +0000 Subject: [PATCH 12/37] fix(agent): make activation handoff safe against reentrant calls Adversarial audit findings: attach/detach may synchronously re-enter activate/deactivate (e.g. via a store subscriber), and a superseded in-flight activate left a stale pending record behind. - Re-check staleness around attach; a superseded request undoes its own attach (best-effort detach) instead of publishing over the winner. - Replace pendingDocumentId with a generation-tagged pending record so a request only clears its own record and deactivate only cancels the in-flight request it actually targets. - Document the DocumentViewBinding contract: detach must tolerate a partially attached binding and is never retried after it throws. --- .../document/activationCoordinator.test.ts | 84 ++++++++++++++++++- .../graph/document/activationCoordinator.ts | 50 +++++++++-- 2 files changed, 125 insertions(+), 9 deletions(-) diff --git a/src/core/graph/document/activationCoordinator.test.ts b/src/core/graph/document/activationCoordinator.test.ts index 5e998efa3ff..dea38132da8 100644 --- a/src/core/graph/document/activationCoordinator.test.ts +++ b/src/core/graph/document/activationCoordinator.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest' -import type { DocumentViewBinding } from '@/core/graph/document/activationCoordinator' +import type { + ActivationOutcome, + DocumentViewBinding +} from '@/core/graph/document/activationCoordinator' import { createActivationCoordinator } from '@/core/graph/document/activationCoordinator' import type { DocumentId } from '@/types/documentId' import { toDocumentId } from '@/types/documentId' @@ -191,7 +194,84 @@ describe('createActivationCoordinator', () => { reason: 'handoff-failed' }) expect(coordinator.activeDocumentId()).toBeNull() - // The previous document was detached exactly once before the failure. + // The previous document was detached exactly once before the failure, + // and the failed binding received a best-effort undo-detach. + expect(log).toEqual([ + `attach:a:${docA}`, + `detach:a:${docA}`, + `detach:b:${docB}` + ]) + }) + + it('a reentrant deactivate from within attach supersedes the activation', async () => { + const coordinator = createActivationCoordinator({ isLoaded: () => true }) + const log: string[] = [] + const docB = toDocumentId('doc-b') + const reentrantBinding: DocumentViewBinding = { + attach: (id) => { + log.push(`attach:b:${id}`) + coordinator.deactivate(docB) + }, + detach: (id) => log.push(`detach:b:${id}`) + } + + const outcome = await coordinator.activate(docB, reentrantBinding) + + expect(outcome).toEqual({ status: 'superseded', documentId: docB }) + expect(coordinator.activeDocumentId()).toBeNull() + // The attach was undone instead of publishing over the deactivate. + expect(log).toEqual([`attach:b:${docB}`, `detach:b:${docB}`]) + }) + + it('a reentrant activate from within detach wins over the in-progress handoff', async () => { + const coordinator = createActivationCoordinator({ isLoaded: () => true }) + const log: string[] = [] + const docA = toDocumentId('doc-a') + const docB = toDocumentId('doc-b') + const docC = toDocumentId('doc-c') + let reentrant: Promise | undefined + const bindingA: DocumentViewBinding = { + attach: (id) => log.push(`attach:a:${id}`), + detach: (id) => { + log.push(`detach:a:${id}`) + reentrant = coordinator.activate(docC, recordingBinding(log, 'c')) + } + } + await coordinator.activate(docA, bindingA) + + const outcome = await coordinator.activate(docB, recordingBinding(log, 'b')) + + expect(outcome).toEqual({ status: 'superseded', documentId: docB }) + expect(await reentrant).toEqual({ status: 'activated', documentId: docC }) + expect(coordinator.activeDocumentId()).toBe(docC) + // B never attached; C attached exactly once after A's detach. + expect(log).toEqual([ + `attach:a:${docA}`, + `detach:a:${docA}`, + `attach:c:${docC}` + ]) + }) + + it('deactivate of a superseded in-flight document is a no-op', async () => { + const slowHydration = deferred() + const docA = toDocumentId('doc-a') + const docB = toDocumentId('doc-b') + const coordinator = createActivationCoordinator({ + isLoaded: () => true, + hydrate: (id) => (id === docB ? slowHydration.promise : Promise.resolve()) + }) + const log: string[] = [] + await coordinator.activate(docA, recordingBinding(log, 'a')) + + const inFlight = coordinator.activate(docB, recordingBinding(log, 'b')) + expect(coordinator.deactivate(docA)).toBe(true) + slowHydration.resolve() + expect(await inFlight).toEqual({ status: 'superseded', documentId: docB }) + + // The superseded request cleared its own pending record, so deactivating + // the never-activated document reports that nothing was cancelled. + expect(coordinator.deactivate(docB)).toBe(false) + expect(coordinator.activeDocumentId()).toBeNull() expect(log).toEqual([`attach:a:${docA}`, `detach:a:${docA}`]) }) diff --git a/src/core/graph/document/activationCoordinator.ts b/src/core/graph/document/activationCoordinator.ts index 97ca3b18575..28a99faa2f2 100644 --- a/src/core/graph/document/activationCoordinator.ts +++ b/src/core/graph/document/activationCoordinator.ts @@ -5,6 +5,11 @@ import type { DocumentId } from '@/types/documentId' * renderer/canvas binding, render-attached caches, viewport projection, and * input/event hooks. Attach and detach must not touch semantic document * state (ADR-0024: activation is presentation). + * + * Contract: the coordinator may call `detach` to undo an `attach` that threw + * or was superseded mid-handoff, so `detach` must tolerate a partially + * attached binding. A throwing `detach` should best-effort clean up first; + * the coordinator treats it as detached and never retries it. */ export interface DocumentViewBinding { attach(documentId: DocumentId): void @@ -42,7 +47,7 @@ export interface ActivationCoordinatorDeps { */ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { let generation = 0 - let pendingDocumentId: DocumentId | null = null + let pending: { documentId: DocumentId; generation: number } | null = null let active: { documentId: DocumentId; binding: DocumentViewBinding } | null = null @@ -51,10 +56,12 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { binding: DocumentViewBinding ): Promise { const requestGeneration = ++generation - pendingDocumentId = documentId + pending = { documentId, generation: requestGeneration } const stale = (): boolean => requestGeneration !== generation const finish = (outcome: ActivationOutcome): ActivationOutcome => { - if (!stale()) pendingDocumentId = null + // Clear only this request's own pending record: a newer activate may + // have replaced it, and its record must survive this stale finish. + if (pending?.generation === requestGeneration) pending = null return outcome } try { @@ -74,16 +81,45 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { active = null try { if (previous) previous.binding.detach(previous.documentId) + } catch { + // A throwing detach must not leave a stale published binding: a later + // activate/deactivate would detach the old document twice. + return finish({ + status: 'rejected', + documentId, + reason: 'handoff-failed' + }) + } + // detach and attach may synchronously re-enter activate/deactivate (e.g. + // via a store subscriber). The reentrant call wins: re-check staleness + // around attach so this request never publishes over the winner. + if (stale()) return finish({ status: 'superseded', documentId }) + try { binding.attach(documentId) } catch { - // A throwing detach/attach must not leave a stale published binding: a - // later activate/deactivate would detach the old document twice. + // Best-effort cleanup of hooks a partially-run attach installed; the + // binding stays unpublished either way. + try { + binding.detach(documentId) + } catch { + /* treated as detached (DocumentViewBinding contract) */ + } return finish({ status: 'rejected', documentId, reason: 'handoff-failed' }) } + if (stale()) { + // A reentrant call from within attach superseded this request: undo + // the attach instead of publishing over the winner's state. + try { + binding.detach(documentId) + } catch { + /* treated as detached (DocumentViewBinding contract) */ + } + return finish({ status: 'superseded', documentId }) + } active = { documentId, binding } return finish({ status: 'activated', documentId }) } @@ -96,10 +132,10 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { function deactivate(documentId: DocumentId): boolean { // Cancel an in-flight activate for this document even when it has not // been published yet; otherwise the activation would still complete. - const cancelledInFlight = pendingDocumentId === documentId + const cancelledInFlight = pending?.documentId === documentId if (cancelledInFlight) { generation++ - pendingDocumentId = null + pending = null } if (active?.documentId !== documentId) return cancelledInFlight generation++ From df51222520922280f73fce85162911504a101a7f Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 06:17:40 +0000 Subject: [PATCH 13/37] fix(agent): resume strict frame sequencing after a lineage reset resetLineage left expectedSeq null, so a frame lost in transit right after a reset was silently accepted instead of triggering a gap/resync. The new lineage now expects the next frame at atSeq + 1; beginResync keeps expectedSeq null because the host chooses the post-resync seq. --- .../document/detachedTargetSession.test.ts | 18 ++++++++++++++++++ .../graph/document/detachedTargetSession.ts | 4 +++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/core/graph/document/detachedTargetSession.test.ts b/src/core/graph/document/detachedTargetSession.test.ts index 72c0dbc9656..73aefdbd03e 100644 --- a/src/core/graph/document/detachedTargetSession.test.ts +++ b/src/core/graph/document/detachedTargetSession.test.ts @@ -346,6 +346,24 @@ describe('createDetachedTargetSession', () => { freshHost.destroy() }) + it('detects a lost-in-transit frame after a lineage reset as a gap', () => { + const session = createDetachedTargetSession(WORKFLOW_ID) + session.resetLineage(10) + + // The new lineage continues at seq 11; seq 12 means a frame was lost. + const freshHost = new Y.Doc() + setNode(freshHost, '9', { type: 'Fresh' }) + const outcome = session.enqueue({ + workflowId: WORKFLOW_ID, + seq: 12, + update: Y.encodeStateAsUpdate(freshHost) + }) + freshHost.destroy() + + expect(outcome).toEqual({ status: 'gap', expectedSeq: 11, receivedSeq: 12 }) + expect(session.snapshot().needsResync).toBe(true) + }) + it('rejects frames addressed to another target loudly', () => { const session = createDetachedTargetSession(WORKFLOW_ID) const stranger = createFrameSource('wf-other') diff --git a/src/core/graph/document/detachedTargetSession.ts b/src/core/graph/document/detachedTargetSession.ts index b7fd49e110e..0512b908e83 100644 --- a/src/core/graph/document/detachedTargetSession.ts +++ b/src/core/graph/document/detachedTargetSession.ts @@ -207,7 +207,9 @@ export function createDetachedTargetSession( lineage = createUuidv4() committedSeq = atSeq committedSeqFloor = atSeq - expectedSeq = null + // The next frame continues the new lineage contiguously at atSeq + 1; a + // later seq means a frame was lost in transit and must trigger a resync. + expectedSeq = atSeq + 1 lastCommitId = null needsResync = false queue = [] From 634ac4a255709bf378d5b195b9f0ee22868449d5 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 06:19:32 +0000 Subject: [PATCH 14/37] fix(agent): resolve mutation-tracking document id per write call The wrapper previously captured the active document id once at setup, so writes issued after a document switch were tracked against the stale document. Resolve the id inside each tracked call instead. --- .../extensions/agent/AgentPanelRoot.vue | 31 ++++++++++--------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 437fe33cc21..97e470d9083 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -175,30 +175,33 @@ const resolveDocumentId = (workflowId: string) => graphDocumentStore.createDocument({ workflowId }) /** * Record every successful write against the target's document so its - * revision advances (ADR-0024 dirty tracking). Each method re-resolves the - * document id at success time: the workflow may have been rebound to a new - * document between creation and the write. + * revision advances (ADR-0024 dirty tracking). Each method resolves the + * document id when the write starts — not at wrapper creation (the workflow + * may have been rebound to a new document since) and not at success time + * (the write itself can synchronously trigger a rebind, and the mutation + * belongs to the document that was bound when the write began). */ const withMutationTracking = ( inner: GraphMutations, workflowId: string ): GraphMutations => { - const track = (committed: boolean): boolean => { - if (committed) { - const documentId = resolveDocumentId(workflowId) - if (documentId) graphDocumentStore.markMutated(documentId) - } + const tracked = (write: () => boolean): boolean => { + const documentId = resolveDocumentId(workflowId) + const committed = write() + if (committed && documentId) graphDocumentStore.markMutated(documentId) return committed } return { - batch: (context, define) => track(inner.batch(context, define)), - addNode: (payload, context) => track(inner.addNode(payload, context)), + batch: (context, define) => tracked(() => inner.batch(context, define)), + addNode: (payload, context) => + tracked(() => inner.addNode(payload, context)), setWidget: (nodeId, name, value, context) => - track(inner.setWidget(nodeId, name, value, context)), - connect: (link, context) => track(inner.connect(link, context)), + tracked(() => inner.setWidget(nodeId, name, value, context)), + connect: (link, context) => tracked(() => inner.connect(link, context)), deleteNode: (nodeId, removedLinkIds, context) => - track(inner.deleteNode(nodeId, removedLinkIds, context)), - clearSemanticGraph: (context) => track(inner.clearSemanticGraph(context)) + tracked(() => inner.deleteNode(nodeId, removedLinkIds, context)), + clearSemanticGraph: (context) => + tracked(() => inner.clearSemanticGraph(context)) } } const graphMutations = (workflowId: string) => { From 512309e0c90af624002dd09560912338295cf17e Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 06:29:38 +0000 Subject: [PATCH 15/37] fix(agent): don't cancel unrelated in-flight activation on deactivate Deactivate is targeted at the currently active document; bumping the generation counter in the active branch also invalidated an unrelated concurrent activate(), silently dropping its activation. Keep the bump only for the pending-target branch, which is the actual cancellation case. Found by adversarial audit (architect lens, finding 1). --- .../document/activationCoordinator.test.ts | 22 +++++++++++-------- .../graph/document/activationCoordinator.ts | 5 ++++- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/src/core/graph/document/activationCoordinator.test.ts b/src/core/graph/document/activationCoordinator.test.ts index dea38132da8..89a88687915 100644 --- a/src/core/graph/document/activationCoordinator.test.ts +++ b/src/core/graph/document/activationCoordinator.test.ts @@ -135,7 +135,7 @@ describe('createActivationCoordinator', () => { expect(coordinator.activeDocumentId()).toBe(docB) }) - it('deactivate detaches the active document and cancels in-flight activation', async () => { + it('deactivate detaches the active document without cancelling an unrelated in-flight activation', async () => { const slowHydration = deferred() const docA = toDocumentId('doc-a') const docB = toDocumentId('doc-b') @@ -148,11 +148,16 @@ describe('createActivationCoordinator', () => { const inFlight = coordinator.activate(docB, recordingBinding(log, 'b')) expect(coordinator.deactivate(docA)).toBe(true) + expect(coordinator.activeDocumentId()).toBeNull() slowHydration.resolve() - expect(await inFlight).toEqual({ status: 'superseded', documentId: docB }) - expect(coordinator.activeDocumentId()).toBeNull() - expect(log).toEqual([`attach:a:${docA}`, `detach:a:${docA}`]) + expect(await inFlight).toEqual({ status: 'activated', documentId: docB }) + expect(coordinator.activeDocumentId()).toBe(docB) + expect(log).toEqual([ + `attach:a:${docA}`, + `detach:a:${docA}`, + `attach:b:${docB}` + ]) }) it('deactivate cancels an in-flight activate for the same document', async () => { @@ -254,25 +259,24 @@ describe('createActivationCoordinator', () => { it('deactivate of a superseded in-flight document is a no-op', async () => { const slowHydration = deferred() - const docA = toDocumentId('doc-a') const docB = toDocumentId('doc-b') + const docC = toDocumentId('doc-c') const coordinator = createActivationCoordinator({ isLoaded: () => true, hydrate: (id) => (id === docB ? slowHydration.promise : Promise.resolve()) }) const log: string[] = [] - await coordinator.activate(docA, recordingBinding(log, 'a')) const inFlight = coordinator.activate(docB, recordingBinding(log, 'b')) - expect(coordinator.deactivate(docA)).toBe(true) + await coordinator.activate(docC, recordingBinding(log, 'c')) slowHydration.resolve() expect(await inFlight).toEqual({ status: 'superseded', documentId: docB }) // The superseded request cleared its own pending record, so deactivating // the never-activated document reports that nothing was cancelled. expect(coordinator.deactivate(docB)).toBe(false) - expect(coordinator.activeDocumentId()).toBeNull() - expect(log).toEqual([`attach:a:${docA}`, `detach:a:${docA}`]) + expect(coordinator.activeDocumentId()).toBe(docC) + expect(log).toEqual([`attach:c:${docC}`]) }) it('does not detach the previous document twice after a throwing detach', async () => { diff --git a/src/core/graph/document/activationCoordinator.ts b/src/core/graph/document/activationCoordinator.ts index 28a99faa2f2..1e48d91ea5a 100644 --- a/src/core/graph/document/activationCoordinator.ts +++ b/src/core/graph/document/activationCoordinator.ts @@ -138,7 +138,10 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { pending = null } if (active?.documentId !== documentId) return cancelledInFlight - generation++ + // Deactivation is targeted: no generation bump here. Every in-flight + // activate holds a `pending` record (handled above), so bumping the + // generation for the active branch would only supersede an unrelated + // in-flight activate of a different document, which must proceed. const previous = active active = null previous.binding.detach(documentId) From 486db4a6380b381a3988e8c9e2b0e9488313fdf3 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 1 Sep 2026 06:31:03 +0000 Subject: [PATCH 16/37] fix(agent): allow closing documents that never hydrated The 'closed' reducer guard required phase === 'loaded', so a document whose hydration failed (or never ran) could never leave the registry: close was a silent no-op and removeDocument requires a closed phase. Guard against double-close only; a created document still needs an explicit discardChanges since its persistence state is 'unsaved'. Adds a store-level test covering create -> close -> remove without hydration, including workflow-id mapping cleanup. Found by adversarial audit (architect lens, finding 3). --- src/core/graph/document/documentLifecycle.test.ts | 15 ++++++++++++--- src/core/graph/document/documentLifecycle.ts | 4 +++- src/stores/graphDocumentStore.test.ts | 15 +++++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/core/graph/document/documentLifecycle.test.ts b/src/core/graph/document/documentLifecycle.test.ts index 8c0c687ffd0..9c90d6dda9c 100644 --- a/src/core/graph/document/documentLifecycle.test.ts +++ b/src/core/graph/document/documentLifecycle.test.ts @@ -132,12 +132,21 @@ describe('reduceDocument', () => { ).toEqual(closed) }) - it('cannot close a document that was never loaded', () => { - const attempted = reduceDocument(initialDocumentState, { + it('blocks closing a never-loaded document without an explicit discard', () => { + const blocked = reduceDocument(initialDocumentState, { + type: 'closed', + atRevision: 0, + discardChanges: false + }) + expect(blocked.phase).toBe('created') + }) + + it('closes a never-loaded document when changes are explicitly discarded', () => { + const closed = reduceDocument(initialDocumentState, { type: 'closed', atRevision: 0, discardChanges: true }) - expect(attempted.phase).toBe('created') + expect(closed.phase).toBe('closed') }) }) diff --git a/src/core/graph/document/documentLifecycle.ts b/src/core/graph/document/documentLifecycle.ts index 85b97b3e0b5..401e62d8490 100644 --- a/src/core/graph/document/documentLifecycle.ts +++ b/src/core/graph/document/documentLifecycle.ts @@ -64,7 +64,9 @@ export function reduceDocument( return state return { ...state, savedRevision: event.atRevision } case 'closed': { - if (state.phase !== 'loaded') return state + // `created` documents are closable too: a document whose hydration + // failed (or never ran) must not be stuck in the registry forever. + if (state.phase === 'closed') return state if (event.atRevision !== state.revision) return state if (!event.discardChanges && persistenceOf(state) !== 'clean') return state diff --git a/src/stores/graphDocumentStore.test.ts b/src/stores/graphDocumentStore.test.ts index 313cd17d345..5a78488a47c 100644 --- a/src/stores/graphDocumentStore.test.ts +++ b/src/stores/graphDocumentStore.test.ts @@ -69,6 +69,21 @@ describe('useGraphDocumentStore', () => { expect(store.resolveWorkflowTarget('wf-1')?.documentId).toBe(second) }) + it('closes and removes a document whose hydration never ran', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument({ workflowId: 'wf-1' }) + if (documentId === null) throw new Error('createDocument failed') + expect( + store.closeDocument(documentId, { atRevision: 0, discardChanges: false }) + ).toBe(false) + expect( + store.closeDocument(documentId, { atRevision: 0, discardChanges: true }) + ).toBe(true) + expect(store.resolveWorkflowTarget('wf-1')).toBeNull() + expect(store.removeDocument(documentId)).toBe(true) + expect(store.getDocument(documentId)).toBeNull() + }) + it('hydration early-binds the scope without requiring a renderer', () => { const store = useGraphDocumentStore() const documentId = store.createDocument({ workflowId: 'wf-1' }) From 17190d33cf73c273e4d6721518c62e8255bd08c5 Mon Sep 17 00:00:00 2001 From: bymyself Date: Wed, 2 Sep 2026 08:31:42 +0000 Subject: [PATCH 17/37] feat(agent): bind ChangeTracker/ComfyWorkflow dirty tracking to the GraphDocument registry Continues the ADR-0024 document/activation seam (PR #16375, fec16fu-2): production ComfyWorkflow had no documentId binding, so the registry's persistence state (unsaved/clean/dirty) never reflected real local edits. - ComfyWorkflow mints a local-only GraphDocument (no workflow_id) the first time it loads, held for the instance's lifetime across unload/reload (no closer exists yet, so the entry is left standing rather than orphaned by minting a second one). - ChangeTracker.updateModified() calls markMutated() on the bound document whenever activeState moves to a new snapshot (capture, squash, undo, redo all funnel through this one method), so revision advances 1:1 with the existing _isModified recompute. - ComfyWorkflow.save() captures a beginSave() ticket for the exact revision at call time (before any await, including the dynamic workflowDraftStoreV2 import) and completes it after I/O, so a mutation that commits mid-save correctly leaves the document dirty rather than being silently swallowed into the save. Tests: comfyWorkflow.test.ts covers mint-on-load, id reuse across reload, unsaved->clean->dirty transitions, and the mid-save-mutation race. Existing changeTracker.test.ts and graphDocumentStore.test.ts suites pass unchanged (81 tests total across the three files). Not in scope here (left for follow-up): closing/removing documents on tab close, and wiring workflowStore's local documents into the same cloud-workflow_id resolution path the agent panel uses. --- .../management/stores/comfyWorkflow.test.ts | 194 ++++++++++++++++++ .../management/stores/comfyWorkflow.ts | 28 +++ src/scripts/changeTracker.ts | 8 + 3 files changed, 230 insertions(+) create mode 100644 src/platform/workflow/management/stores/comfyWorkflow.test.ts diff --git a/src/platform/workflow/management/stores/comfyWorkflow.test.ts b/src/platform/workflow/management/stores/comfyWorkflow.test.ts new file mode 100644 index 00000000000..942f27014dd --- /dev/null +++ b/src/platform/workflow/management/stores/comfyWorkflow.test.ts @@ -0,0 +1,194 @@ +import { describe, expect, it, vi } from 'vitest' + +import { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' +import { api } from '@/scripts/api' +import { useGraphDocumentStore } from '@/stores/graphDocumentStore' + +vi.mock('@/scripts/api', () => ({ + api: { + getUserData: vi.fn(), + storeUserData: vi.fn() + } +})) + +vi.mock( + '@/platform/workflow/persistence/stores/workflowDraftStoreV2', + () => ({ + useWorkflowDraftStoreV2: vi.fn(() => ({ + getDraft: vi.fn(() => undefined), + markDraftUsed: vi.fn(), + removeDraft: vi.fn() + })) + }) +) + +vi.mock('@/platform/settings/settingStore', () => ({ + useSettingStore: vi.fn(() => ({ + get: vi.fn(() => false) + })) +})) + +vi.mock('@/scripts/app', () => ({ + app: { + graph: {}, + rootGraph: { serialize: vi.fn(() => ({ nodes: [], links: [] })) }, + loadGraphData: vi.fn(() => Promise.resolve()), + canvas: { ds: { scale: 1, offset: [0, 0] } }, + ui: { autoQueueEnabled: false, autoQueueMode: 'instant' } + } +})) + +// `ComfyWorkflow.load()` dynamically imports `changeTracker`, which in turn +// imports these stores. They are unused by the save/document-identity +// behavior under test here, but mirror changeTracker.test.ts's mocks so the +// dynamic import resolves without dragging in their real (DOM/app-bound) +// implementations. +vi.mock('@/stores/executionStore', () => ({ + useExecutionStore: vi.fn(() => ({})) +})) +vi.mock('@/stores/nodeOutputStore', () => ({ + useNodeOutputStore: vi.fn(() => ({ + snapshotOutputs: vi.fn(() => ({})), + restoreOutputs: vi.fn() + })) +})) +vi.mock('@/stores/subgraphNavigationStore', () => ({ + useSubgraphNavigationStore: vi.fn(() => ({ + exportState: vi.fn(() => []), + restoreState: vi.fn() + })) +})) + +function mockLoadResponse(content: string) { + vi.mocked(api.getUserData).mockResolvedValue({ + status: 200, + text: () => Promise.resolve(content) + } as never) +} + +function mockSaveResponse() { + vi.mocked(api.storeUserData).mockResolvedValue({ + json: () => Promise.resolve('workflows/test.json') + } as never) +} + +async function createLoadedWorkflow(path = 'workflows/test.json') { + const workflow = new ComfyWorkflow({ path, modified: 0, size: 10 }) + mockLoadResponse(JSON.stringify({ nodes: [], links: [] })) + await workflow.load() + return workflow +} + +// `load()`'s dynamic `import('@/scripts/changeTracker')` pulls in the +// litegraph module graph; vitest's on-demand transform of that graph is slow +// (not hung) the first time it runs inside a test body rather than at static +// import/collection time, so these tests need a generous timeout. +const LOAD_TIMEOUT = 30_000 + +describe('ComfyWorkflow document identity (ADR-0024)', () => { + it( + 'mints a local-only document id on load', + async () => { + const workflow = await createLoadedWorkflow() + expect(workflow.documentId).not.toBeNull() + + const store = useGraphDocumentStore() + const entry = store.getDocument(workflow.documentId!) + expect(entry).not.toBeNull() + expect(entry?.workflowId).toBeNull() + expect(store.persistenceStateOf(workflow.documentId!)).toBe('unsaved') + }, + LOAD_TIMEOUT + ) + + it( + 'reuses the same document id across a re-entrant load', + async () => { + const workflow = await createLoadedWorkflow() + const firstId = workflow.documentId + mockLoadResponse(JSON.stringify({ nodes: [], links: [] })) + await workflow.load({ force: true }) + expect(workflow.documentId).toBe(firstId) + }, + LOAD_TIMEOUT + ) + + it( + 'keeps the same document id across unload (no closer exists yet)', + async () => { + const workflow = await createLoadedWorkflow() + const firstId = workflow.documentId + workflow.unload() + // unload() does not clear documentId — the registry entry for the old + // load is left standing until an explicit close, matching the + // create-on-load/no-close-yet lifecycle documented on the field. + expect(workflow.documentId).toBe(firstId) + }, + LOAD_TIMEOUT + ) + + it( + 'advances the document from unsaved to clean at the exact saved revision', + async () => { + const workflow = await createLoadedWorkflow() + const store = useGraphDocumentStore() + const documentId = workflow.documentId! + expect(store.persistenceStateOf(documentId)).toBe('unsaved') + + mockSaveResponse() + await workflow.save() + + expect(store.persistenceStateOf(documentId)).toBe('clean') + }, + LOAD_TIMEOUT + ) + + it( + 'reports dirty for a mutation committed after the last save', + async () => { + const workflow = await createLoadedWorkflow() + const store = useGraphDocumentStore() + const documentId = workflow.documentId! + + mockSaveResponse() + await workflow.save() + expect(store.persistenceStateOf(documentId)).toBe('clean') + + store.markMutated(documentId) + expect(store.persistenceStateOf(documentId)).toBe('dirty') + }, + LOAD_TIMEOUT + ) + + it( + 'leaves the document dirty when a mutation commits mid-save', + async () => { + const workflow = await createLoadedWorkflow() + const store = useGraphDocumentStore() + const documentId = workflow.documentId! + + // Establish a saved baseline first so a later revision divergence can + // actually be observed as 'dirty' rather than 'unsaved'. + mockSaveResponse() + await workflow.save() + + // storeUserData resolves only after a mutation commits against the + // same document, simulating a concurrent edit racing the in-flight + // save. + let resolveSave!: (value: { json: () => Promise }) => void + vi.mocked(api.storeUserData).mockReturnValue( + new Promise((resolve) => { + resolveSave = resolve + }) as never + ) + + const savePromise = workflow.save() + store.markMutated(documentId) + resolveSave({ json: () => Promise.resolve('workflows/test.json') }) + await savePromise + + expect(store.persistenceStateOf(documentId)).toBe('dirty') + }, + LOAD_TIMEOUT + ) +}) diff --git a/src/platform/workflow/management/stores/comfyWorkflow.ts b/src/platform/workflow/management/stores/comfyWorkflow.ts index 3419de24f41..bdb504dff3a 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.ts @@ -2,6 +2,7 @@ import { markRaw } from 'vue' import { t } from '@/i18n' import type { ChangeTracker } from '@/scripts/changeTracker' +import { useGraphDocumentStore } from '@/stores/graphDocumentStore' import { UserFile } from '@/stores/userFileStore' import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' import type { MissingModelCandidate } from '@/platform/missingModel/types' @@ -9,6 +10,7 @@ import type { MissingMediaCandidate } from '@/platform/missingMedia/types' import type { MissingNodeType } from '@/types/comfy' import type { NodeLocatorId } from '@/types/nodeIdentification' import type { SerializedNodeId } from '@/types/nodeId' +import type { DocumentId } from '@/types/documentId' import type { AppMode } from '@/utils/appMode' import type { WidgetId } from '@/types/widgetId' import { generateUUID } from '@/utils/formatUtil' @@ -43,6 +45,15 @@ export class ComfyWorkflow extends UserFile { * The change tracker for the workflow. Non-reactive raw object. */ changeTracker: ChangeTracker | null = null + /** + * This workflow's `GraphDocument` registry identity (ADR-0024). Created + * local-only (no `workflow_id`) the first time the workflow is loaded and + * held for the instance's lifetime; cleared on unload. A fresh load call + * after unload mints a new document id — the registry entry for the old + * one is left for the caller to close, matching `changeTracker`'s own + * create-on-load/null-on-unload lifecycle. + */ + documentId: DocumentId | null = null /** * Whether the workflow has been modified comparing to the initial state. */ @@ -152,6 +163,12 @@ export class ComfyWorkflow extends UserFile { const initialState = JSON.parse(this.originalContent) const { ChangeTracker } = await import('@/scripts/changeTracker') this.changeTracker = markRaw(new ChangeTracker(this, initialState)) + // Local-only document identity (ADR-0024): every loaded workflow gets a + // registry entry, whether or not it is ever bound to a cloud + // `workflow_id` (that mapping is layered on separately, e.g. by the + // agent panel). Minted once per load; reused across re-entrant loads of + // an already-loaded instance. + this.documentId ??= useGraphDocumentStore().createDocument() if (draftState && draftContent) { this.changeTracker.activeState = draftState this.content = draftContent @@ -170,6 +187,16 @@ export class ComfyWorkflow extends UserFile { } override async save() { + // Capture the save ticket before any `await` (including the dynamic + // import below): a mutation that commits while this call is in flight + // must leave the document dirty, so the baseline can only advance to the + // revision captured here — the revision at the instant `save()` was + // invoked — never to whatever revision happens to be current once + // control returns to us after yielding. + const documentId = this.documentId + const graphDocumentStore = documentId ? useGraphDocumentStore() : null + const saveTicket = graphDocumentStore?.beginSave(documentId!) ?? null + const { useWorkflowDraftStoreV2 } = await import('@/platform/workflow/persistence/stores/workflowDraftStoreV2') const draftStore = useWorkflowDraftStoreV2() @@ -177,6 +204,7 @@ export class ComfyWorkflow extends UserFile { // Force save to ensure the content is updated in remote storage incase // the isModified state is screwed by changeTracker. const ret = await super.save({ force: true }) + if (saveTicket) graphDocumentStore!.completeSave(saveTicket) this.changeTracker?.reset() this.isModified = false draftStore.removeDraft(this.path) diff --git a/src/scripts/changeTracker.ts b/src/scripts/changeTracker.ts index 79199aa614e..602f633a93c 100644 --- a/src/scripts/changeTracker.ts +++ b/src/scripts/changeTracker.ts @@ -11,6 +11,7 @@ import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/w import type { ExecutedWsMessage } from '@/schemas/apiSchema' import { useDialogStore } from '@/stores/dialogStore' import { useExecutionStore } from '@/stores/executionStore' +import { useGraphDocumentStore } from '@/stores/graphDocumentStore' import { useNodeOutputStore } from '@/stores/nodeOutputStore' import { useQueueSettingsStore } from '@/stores/queueSettingsStore' import { useSubgraphNavigationStore } from '@/stores/subgraphNavigationStore' @@ -373,6 +374,13 @@ export class ChangeTracker { this.initialState, this.activeState ) + // Every call site of updateModified() already gated on a real state + // change (activeState just moved to a new snapshot), so this maps 1:1 + // onto the registry's "mutated" event (ADR-0024 dirty tracking). + // Undo/redo call in too: moving activeState to a prior/later snapshot + // is still a committed change to the document's current content. + if (workflow.documentId) + useGraphDocumentStore().markMutated(workflow.documentId) } const autoQueueGraphChanged = From a264be44dd79bdea67e0fac80c7c9480fcd73108 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Wed, 2 Sep 2026 08:37:05 +0000 Subject: [PATCH 18/37] [automated] Apply ESLint and Oxfmt fixes --- .../management/stores/comfyWorkflow.test.ts | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/src/platform/workflow/management/stores/comfyWorkflow.test.ts b/src/platform/workflow/management/stores/comfyWorkflow.test.ts index 942f27014dd..88f22b9de0a 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.test.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.test.ts @@ -11,16 +11,13 @@ vi.mock('@/scripts/api', () => ({ } })) -vi.mock( - '@/platform/workflow/persistence/stores/workflowDraftStoreV2', - () => ({ - useWorkflowDraftStoreV2: vi.fn(() => ({ - getDraft: vi.fn(() => undefined), - markDraftUsed: vi.fn(), - removeDraft: vi.fn() - })) - }) -) +vi.mock('@/platform/workflow/persistence/stores/workflowDraftStoreV2', () => ({ + useWorkflowDraftStoreV2: vi.fn(() => ({ + getDraft: vi.fn(() => undefined), + markDraftUsed: vi.fn(), + removeDraft: vi.fn() + })) +})) vi.mock('@/platform/settings/settingStore', () => ({ useSettingStore: vi.fn(() => ({ From 0073af05314de7fb1b9c92671abfd730775da8fa Mon Sep 17 00:00:00 2001 From: bymyself Date: Wed, 2 Sep 2026 14:43:03 +0000 Subject: [PATCH 19/37] fix(agent): harden document activation lifecycle --- .../document/activationCoordinator.test.ts | 14 ++++++++ .../graph/document/activationCoordinator.ts | 6 +++- .../document/detachedTargetSession.test.ts | 13 ++++++++ .../graph/document/detachedTargetSession.ts | 4 +++ .../graph/document/documentLifecycle.test.ts | 3 ++ src/core/graph/document/documentLifecycle.ts | 2 +- .../management/stores/comfyWorkflow.test.ts | 30 +++++++++++++++-- .../management/stores/comfyWorkflow.ts | 20 +++++++----- src/stores/graphDocumentStore.test.ts | 5 +-- ...tActivationPersistence.integration.test.ts | 4 ++- .../agent/crdt/targetFrameProjection.test.ts | 32 +++++++++++++++++-- .../agent/crdt/targetFrameProjection.ts | 10 ++++-- 12 files changed, 123 insertions(+), 20 deletions(-) diff --git a/src/core/graph/document/activationCoordinator.test.ts b/src/core/graph/document/activationCoordinator.test.ts index 89a88687915..544c31ea50e 100644 --- a/src/core/graph/document/activationCoordinator.test.ts +++ b/src/core/graph/document/activationCoordinator.test.ts @@ -317,4 +317,18 @@ describe('createActivationCoordinator', () => { expect(coordinator.deactivate(docB)).toBe(false) expect(coordinator.activeDocumentId()).toBe(docA) }) + + it('treats a throwing detach during deactivate as detached', async () => { + const coordinator = createActivationCoordinator({ isLoaded: () => true }) + const docA = toDocumentId('doc-a') + await coordinator.activate(docA, { + attach: () => {}, + detach: () => { + throw new Error('detach boom') + } + }) + + expect(coordinator.deactivate(docA)).toBe(true) + expect(coordinator.activeDocumentId()).toBeNull() + }) }) diff --git a/src/core/graph/document/activationCoordinator.ts b/src/core/graph/document/activationCoordinator.ts index 1e48d91ea5a..7b2edebff09 100644 --- a/src/core/graph/document/activationCoordinator.ts +++ b/src/core/graph/document/activationCoordinator.ts @@ -144,7 +144,11 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { // in-flight activate of a different document, which must proceed. const previous = active active = null - previous.binding.detach(documentId) + try { + previous.binding.detach(documentId) + } catch { + /* treated as detached (DocumentViewBinding contract) */ + } return true } diff --git a/src/core/graph/document/detachedTargetSession.test.ts b/src/core/graph/document/detachedTargetSession.test.ts index 73aefdbd03e..51c53ef4da4 100644 --- a/src/core/graph/document/detachedTargetSession.test.ts +++ b/src/core/graph/document/detachedTargetSession.test.ts @@ -190,6 +190,19 @@ describe('createDetachedTargetSession', () => { expect(session.snapshot().committedSeq).toBeNull() }) + it('cannot enqueue or commit after destruction', () => { + const session = createDetachedTargetSession(WORKFLOW_ID) + const source = createFrameSource() + session.destroy() + + expect( + session.enqueue( + source.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + ).toEqual({ status: 'resync-required' }) + expect(session.commitNext(acceptAll)).toEqual({ status: 'idle' }) + }) + it('skips duplicate frames at or below the last accepted sequence', () => { const source = createFrameSource() const session = createDetachedTargetSession(WORKFLOW_ID) diff --git a/src/core/graph/document/detachedTargetSession.ts b/src/core/graph/document/detachedTargetSession.ts index 0512b908e83..670689f99ef 100644 --- a/src/core/graph/document/detachedTargetSession.ts +++ b/src/core/graph/document/detachedTargetSession.ts @@ -95,6 +95,7 @@ export function createDetachedTargetSession( /** `null` accepts any sequence (fresh session or just resynced). */ let expectedSeq: number | null = null let queue: TargetFrame[] = [] + let destroyed = false function assertTarget(frameWorkflowId: string): void { if (frameWorkflowId !== workflowId) { @@ -106,6 +107,7 @@ export function createDetachedTargetSession( } function enqueue(frame: TargetFrame): EnqueueResult { + if (destroyed) return { status: 'resync-required' } assertTarget(frame.workflowId) if (needsResync) return { status: 'resync-required' } @@ -133,6 +135,7 @@ export function createDetachedTargetSession( } function commitNext(port: TargetFrameApplyPort): CommitResult { + if (destroyed) return { status: 'idle' } if (needsResync) return { status: 'resync-required' } const frame = queue[0] if (!frame) return { status: 'idle' } @@ -242,6 +245,7 @@ export function createDetachedTargetSession( } function destroy(): void { + destroyed = true committedDoc.destroy() queue = [] } diff --git a/src/core/graph/document/documentLifecycle.test.ts b/src/core/graph/document/documentLifecycle.test.ts index 9c90d6dda9c..12d29920582 100644 --- a/src/core/graph/document/documentLifecycle.test.ts +++ b/src/core/graph/document/documentLifecycle.test.ts @@ -69,6 +69,9 @@ describe('reduceDocument', () => { expect( reduceDocument(state, { type: 'saveCompleted', atRevision: 0 }) ).toEqual(state) + expect( + reduceDocument(state, { type: 'saveCompleted', atRevision: 1 }) + ).toBe(state) }) it('remote or human mutations after a save make a loaded document dirty again', () => { diff --git a/src/core/graph/document/documentLifecycle.ts b/src/core/graph/document/documentLifecycle.ts index 401e62d8490..733355aa679 100644 --- a/src/core/graph/document/documentLifecycle.ts +++ b/src/core/graph/document/documentLifecycle.ts @@ -59,7 +59,7 @@ export function reduceDocument( if (event.atRevision > state.revision) return state if ( state.savedRevision !== null && - event.atRevision < state.savedRevision + event.atRevision <= state.savedRevision ) return state return { ...state, savedRevision: event.atRevision } diff --git a/src/platform/workflow/management/stores/comfyWorkflow.test.ts b/src/platform/workflow/management/stores/comfyWorkflow.test.ts index 88f22b9de0a..33af00dee4a 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.test.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.test.ts @@ -1,13 +1,15 @@ import { describe, expect, it, vi } from 'vitest' import { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' +import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { api } from '@/scripts/api' import { useGraphDocumentStore } from '@/stores/graphDocumentStore' vi.mock('@/scripts/api', () => ({ api: { getUserData: vi.fn(), - storeUserData: vi.fn() + storeUserData: vi.fn(), + dispatchCustomEvent: vi.fn() } })) @@ -161,6 +163,7 @@ describe('ComfyWorkflow document identity (ADR-0024)', () => { 'leaves the document dirty when a mutation commits mid-save', async () => { const workflow = await createLoadedWorkflow() + useWorkflowStore().attachWorkflow(workflow) const store = useGraphDocumentStore() const documentId = workflow.documentId! @@ -180,10 +183,33 @@ describe('ComfyWorkflow document identity (ADR-0024)', () => { ) const savePromise = workflow.save() - store.markMutated(documentId) + const previousState = workflow.changeTracker!.activeState + workflow.changeTracker!.activeState = { + ...previousState, + nodes: [ + { + id: 1, + type: 'KSampler', + pos: [0, 0], + size: [100, 100], + flags: {}, + order: 0, + mode: 0, + inputs: [], + outputs: [], + properties: {} + } + ] + } + workflow.changeTracker!.updateModified(previousState) resolveSave({ json: () => Promise.resolve('workflows/test.json') }) await savePromise + expect(api.storeUserData).toHaveBeenCalledWith( + workflow.path, + JSON.stringify(previousState), + expect.anything() + ) expect(store.persistenceStateOf(documentId)).toBe('dirty') }, LOAD_TIMEOUT diff --git a/src/platform/workflow/management/stores/comfyWorkflow.ts b/src/platform/workflow/management/stores/comfyWorkflow.ts index bdb504dff3a..b469e140fce 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.ts @@ -48,10 +48,8 @@ export class ComfyWorkflow extends UserFile { /** * This workflow's `GraphDocument` registry identity (ADR-0024). Created * local-only (no `workflow_id`) the first time the workflow is loaded and - * held for the instance's lifetime; cleared on unload. A fresh load call - * after unload mints a new document id — the registry entry for the old - * one is left for the caller to close, matching `changeTracker`'s own - * create-on-load/null-on-unload lifecycle. + * held for the instance's lifetime. Unload retains it, and later loads of + * the same instance reuse it until an explicit document closer is wired. */ documentId: DocumentId | null = null /** @@ -196,18 +194,24 @@ export class ComfyWorkflow extends UserFile { const documentId = this.documentId const graphDocumentStore = documentId ? useGraphDocumentStore() : null const saveTicket = graphDocumentStore?.beginSave(documentId!) ?? null + const content = JSON.stringify(this.activeState) const { useWorkflowDraftStoreV2 } = await import('@/platform/workflow/persistence/stores/workflowDraftStoreV2') const draftStore = useWorkflowDraftStoreV2() - this.content = JSON.stringify(this.activeState) + this.content = content // Force save to ensure the content is updated in remote storage incase // the isModified state is screwed by changeTracker. const ret = await super.save({ force: true }) if (saveTicket) graphDocumentStore!.completeSave(saveTicket) - this.changeTracker?.reset() - this.isModified = false - draftStore.removeDraft(this.path) + const savedCurrentRevision = + saveTicket === null || + graphDocumentStore?.persistenceStateOf(saveTicket.documentId) === 'clean' + if (savedCurrentRevision) { + this.changeTracker?.reset() + this.isModified = false + draftStore.removeDraft(this.path) + } return ret } diff --git a/src/stores/graphDocumentStore.test.ts b/src/stores/graphDocumentStore.test.ts index 5a78488a47c..de727c7609e 100644 --- a/src/stores/graphDocumentStore.test.ts +++ b/src/stores/graphDocumentStore.test.ts @@ -1,4 +1,5 @@ -import { createPinia, setActivePinia } from 'pinia' +import { createTestingPinia } from '@pinia/testing' +import { setActivePinia } from 'pinia' import { beforeEach, describe, expect, it } from 'vitest' import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' @@ -12,7 +13,7 @@ const scope = { describe('useGraphDocumentStore', () => { beforeEach(() => { - setActivePinia(createPinia()) + setActivePinia(createTestingPinia({ stubActions: false })) }) it('creates local-only documents that are not agent-addressable', () => { diff --git a/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts b/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts index c0f8456197b..3d4931ff706 100644 --- a/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts +++ b/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts @@ -159,11 +159,13 @@ describe('document activation persistence (ADR-0024 seam)', () => { 'detach:nodes2' ]) + expect(registry.markMutated(documentId)).toBe(true) const ticket = registry.beginSave(documentId) expect(ticket).not.toBeNull() const savedBytes = serializeDocumentScope(scope) + expect(registry.markMutated(documentId)).toBe(true) expect(registry.completeSave(ticket!)).toBe(true) - expect(registry.persistenceStateOf(documentId)).toBe('clean') + expect(registry.persistenceStateOf(documentId)).toBe('dirty') const reloadSession = createDetachedTargetSession('wf') reloadSession.enqueue({ diff --git a/src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts b/src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts index 36af26fe654..34d93da5316 100644 --- a/src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts +++ b/src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts @@ -10,7 +10,7 @@ type RecordedCall = | { kind: 'reconcileNode'; id: unknown; type: unknown } | { kind: 'connect'; id: unknown } -function recordingMutations(): { +function recordingMutations(batchResult = true): { mutations: GraphMutations calls: RecordedCall[] contexts: unknown[] @@ -37,7 +37,7 @@ function recordingMutations(): { deleteNode: fail, clearSemanticGraph: () => calls.push({ kind: 'clearSemanticGraph' }) }) - return true + return batchResult }, addNode: fail, setWidget: fail, @@ -117,4 +117,32 @@ describe('createTargetFrameApplyPort', () => { expect(applied).toBe(false) expect(calls).toEqual([]) }) + + it('propagates a failed batch commit', () => { + const doc = new Y.Doc() + setNode(doc, '1', { type: 'Source' }) + const { mutations } = recordingMutations(false) + + expect(createTargetFrameApplyPort(mutations).apply(frame, doc)).toBe(false) + }) + + it('uses replay stamps and only clears for an empty document', () => { + const doc = new Y.Doc() + const { mutations, calls, contexts } = recordingMutations() + + expect( + createTargetFrameApplyPort(mutations).apply( + { + workflowId: 'wf-projection', + seq: 1, + update: new Uint8Array() + }, + doc + ) + ).toBe(true) + expect(calls).toEqual([{ kind: 'clearSemanticGraph' }]) + expect(contexts).toEqual([ + { source: 'agent-remote', actor: 'agent-replay', opId: 'replay' } + ]) + }) }) diff --git a/src/workbench/extensions/agent/crdt/targetFrameProjection.ts b/src/workbench/extensions/agent/crdt/targetFrameProjection.ts index ca0e52a355c..75b1b87f22c 100644 --- a/src/workbench/extensions/agent/crdt/targetFrameProjection.ts +++ b/src/workbench/extensions/agent/crdt/targetFrameProjection.ts @@ -120,9 +120,13 @@ export function createTargetFrameApplyPort( const nodeIds = [...nodesMap(stagedDoc).keys()].sort((left, right) => compareNodeIds(toNodeId(left), toNodeId(right)) ) - const linkIds = [...linksMap(stagedDoc).keys()].sort( - (left, right) => Number(left) - Number(right) - ) + const linkIds = [...linksMap(stagedDoc).keys()].sort((left, right) => { + const leftNumber = Number(left) + const rightNumber = Number(right) + if (Number.isFinite(leftNumber) && Number.isFinite(rightNumber)) + return leftNumber - rightNumber + return left < right ? -1 : left > right ? 1 : 0 + }) // Read and validate the whole snapshot before touching the stores: a // malformed entry rejects the frame outright instead of applying a From 000dee93affa2d3dc89080b604bdda3f263641ff Mon Sep 17 00:00:00 2001 From: bymyself Date: Wed, 2 Sep 2026 14:51:21 +0000 Subject: [PATCH 20/37] test(agent): keep projection harness merge-compatible --- .../agent/crdt/targetFrameProjection.test.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts b/src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts index 34d93da5316..5612d37ff05 100644 --- a/src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts +++ b/src/workbench/extensions/agent/crdt/targetFrameProjection.test.ts @@ -2,7 +2,11 @@ import { describe, expect, it } from 'vitest' import * as Y from 'yjs' import type { TargetFrame } from '@/core/graph/document/detachedTargetSession' -import type { GraphMutations } from '@/core/graph/graphMutations' +import type { + GraphMutations, + SemanticLinkPayload, + SemanticNodePayload +} from '@/core/graph/graphMutations' import { createTargetFrameApplyPort } from '@/workbench/extensions/agent/crdt/targetFrameProjection' type RecordedCall = @@ -23,20 +27,23 @@ function recordingMutations(batchResult = true): { const mutations: GraphMutations = { batch(context, define) { contexts.push(context) - define({ + const batch = { addNode: fail, - reconcileNode: (payload) => + reconcileNode: (payload: SemanticNodePayload) => calls.push({ kind: 'reconcileNode', id: payload.id, type: payload.type }), setWidget: fail, - connect: (link) => calls.push({ kind: 'connect', id: link.id }), + connect: (link: SemanticLinkPayload) => + calls.push({ kind: 'connect', id: link.id }), + removeMissing: fail, removeLinks: fail, deleteNode: fail, clearSemanticGraph: () => calls.push({ kind: 'clearSemanticGraph' }) - }) + } + define(batch) return batchResult }, addNode: fail, From 8867729f676d3022a12b2d47fc9c70c15a9bbd21 Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 3 Sep 2026 13:25:58 +0000 Subject: [PATCH 21/37] feat(agent): add document graph lease lifecycle --- src/stores/graphDocumentStore.test.ts | 62 +++++++++++++++++++++- src/stores/graphDocumentStore.ts | 75 +++++++++++++++++++++++++++ 2 files changed, 136 insertions(+), 1 deletion(-) diff --git a/src/stores/graphDocumentStore.test.ts b/src/stores/graphDocumentStore.test.ts index de727c7609e..1f27524eac7 100644 --- a/src/stores/graphDocumentStore.test.ts +++ b/src/stores/graphDocumentStore.test.ts @@ -1,6 +1,6 @@ import { createTestingPinia } from '@pinia/testing' import { setActivePinia } from 'pinia' -import { beforeEach, describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' @@ -193,4 +193,64 @@ describe('useGraphDocumentStore', () => { expect(store.getDocument(a)?.state.revision).toBe(1) expect(store.getDocument(b)?.state.revision).toBe(0) }) + + it('publishes only the newest graph hydration and disposes stale results', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument() + if (documentId === null) throw new Error('createDocument failed') + const first = store.beginGraphHydration(documentId)! + const second = store.beginGraphHydration(documentId)! + const staleDispose = vi.fn() + const winningDispose = vi.fn() + const stale = { graph: { id: 'stale' }, dispose: staleDispose } + const winning = { graph: { id: 'winning' }, dispose: winningDispose } + + expect(store.completeGraphHydration(first, stale)).toBe(false) + expect(staleDispose).toHaveBeenCalledOnce() + expect(store.completeGraphHydration(second, winning)).toBe(true) + expect(store.graphLeaseOf(documentId)).toBe(winning) + expect(winningDispose).not.toHaveBeenCalled() + }) + + it('disposes replaced and closed graph leases exactly once', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument() + if (documentId === null) throw new Error('createDocument failed') + store.hydrateDocument(documentId, scope) + const firstDispose = vi.fn() + const secondDispose = vi.fn() + store.completeGraphHydration(store.beginGraphHydration(documentId)!, { + graph: { id: 'first' }, + dispose: firstDispose + }) + store.completeGraphHydration(store.beginGraphHydration(documentId)!, { + graph: { id: 'second' }, + dispose: secondDispose + }) + + expect(firstDispose).toHaveBeenCalledOnce() + expect( + store.closeDocument(documentId, { atRevision: 0, discardChanges: true }) + ).toBe(true) + expect(secondDispose).toHaveBeenCalledOnce() + expect(store.disposeGraphLease(documentId)).toBe(false) + expect(secondDispose).toHaveBeenCalledOnce() + }) + + it('disposes hydration that completes after close', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument() + if (documentId === null) throw new Error('createDocument failed') + const ticket = store.beginGraphHydration(documentId)! + const dispose = vi.fn() + + expect( + store.closeDocument(documentId, { atRevision: 0, discardChanges: true }) + ).toBe(true) + expect(store.completeGraphHydration(ticket, { graph: {}, dispose })).toBe( + false + ) + expect(dispose).toHaveBeenCalledOnce() + expect(store.graphLeaseOf(documentId)).toBeNull() + }) }) diff --git a/src/stores/graphDocumentStore.ts b/src/stores/graphDocumentStore.ts index dfbc807a735..47b47a5ca37 100644 --- a/src/stores/graphDocumentStore.ts +++ b/src/stores/graphDocumentStore.ts @@ -29,6 +29,17 @@ export interface SaveTicket { readonly revision: number } +/** Opaque host graph capability owned and disposed by the document registry. */ +export interface DocumentGraphLease { + readonly graph: unknown + dispose(): void +} + +export interface GraphHydrationTicket { + readonly documentId: DocumentId + readonly generation: number +} + /** * The GraphDocument registry (ADR-0024): every workflow document is a * first-class entry keyed by a stable frontend `document_id`, whether or not @@ -40,6 +51,11 @@ export interface SaveTicket { export const useGraphDocumentStore = defineStore('graphDocument', () => { const documents = shallowReactive(new Map()) const documentIdByWorkflowId = shallowReactive(new Map()) + const graphLeases = new Map< + DocumentId, + { generation: number; lease: DocumentGraphLease } + >() + const hydrationGenerations = new Map() function getDocument(documentId: DocumentId): GraphDocumentEntry | null { return documents.get(documentId) ?? null @@ -61,6 +77,54 @@ export const useGraphDocumentStore = defineStore('graphDocument', () => { return entry ? persistenceOf(entry.state) : null } + function graphLeaseOf(documentId: DocumentId): DocumentGraphLease | null { + return graphLeases.get(documentId)?.lease ?? null + } + + function beginGraphHydration( + documentId: DocumentId + ): GraphHydrationTicket | null { + const entry = documents.get(documentId) + if (!entry || entry.state.phase === 'closed') return null + const generation = (hydrationGenerations.get(documentId) ?? 0) + 1 + hydrationGenerations.set(documentId, generation) + return { documentId, generation } + } + + /** + * Publish only the newest hydration result. Replaced and stale leases are + * disposed exactly once by registry ownership. + */ + function completeGraphHydration( + ticket: GraphHydrationTicket, + lease: DocumentGraphLease + ): boolean { + const entry = documents.get(ticket.documentId) + if ( + !entry || + entry.state.phase === 'closed' || + hydrationGenerations.get(ticket.documentId) !== ticket.generation + ) { + lease.dispose() + return false + } + const previous = graphLeases.get(ticket.documentId) + graphLeases.set(ticket.documentId, { + generation: ticket.generation, + lease + }) + if (previous && previous.lease !== lease) previous.lease.dispose() + return true + } + + function disposeGraphLease(documentId: DocumentId): boolean { + const current = graphLeases.get(documentId) + if (!current) return false + graphLeases.delete(documentId) + current.lease.dispose() + return true + } + function patch( documentId: DocumentId, changes: Partial> @@ -176,6 +240,12 @@ export const useGraphDocumentStore = defineStore('graphDocument', () => { discardChanges: decision.discardChanges }) if (state.phase !== 'closed' || entry.state.phase === 'closed') return false + // Invalidate in-flight hydration before disposing the published lease. + hydrationGenerations.set( + documentId, + (hydrationGenerations.get(documentId) ?? 0) + 1 + ) + disposeGraphLease(documentId) patch(documentId, { state, scope: null }) return true } @@ -190,6 +260,7 @@ export const useGraphDocumentStore = defineStore('graphDocument', () => { ) documentIdByWorkflowId.delete(entry.workflowId) documents.delete(documentId) + hydrationGenerations.delete(documentId) return true } @@ -198,6 +269,10 @@ export const useGraphDocumentStore = defineStore('graphDocument', () => { getDocument, resolveWorkflowTarget, persistenceStateOf, + graphLeaseOf, + beginGraphHydration, + completeGraphHydration, + disposeGraphLease, assignWorkflowId, hydrateDocument, rebindScope, From 9257f4ac29f978d275001d91d1529f5abbbdf459 Mon Sep 17 00:00:00 2001 From: Pipeline Agent Date: Thu, 3 Sep 2026 19:24:52 +0000 Subject: [PATCH 22/37] fix(agent): satisfy current document diagnostics lint --- .../graph/document/detachedTargetSession.test.ts | 8 ++++---- src/core/graph/document/detachedTargetSession.ts | 14 ++++++-------- src/core/graph/document/documentSerializer.test.ts | 8 ++++---- src/core/graph/document/documentSerializer.ts | 7 +++++-- ...cumentActivationPersistence.integration.test.ts | 4 ++-- 5 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/core/graph/document/detachedTargetSession.test.ts b/src/core/graph/document/detachedTargetSession.test.ts index 51c53ef4da4..306200465c3 100644 --- a/src/core/graph/document/detachedTargetSession.test.ts +++ b/src/core/graph/document/detachedTargetSession.test.ts @@ -103,10 +103,10 @@ describe('createDetachedTargetSession', () => { session.commitNext(port) expect(seen).toHaveLength(1) - expect(seen[0]!.frame.actor).toBe('agent:planner') - expect(seen[0]!.frame.opIds).toEqual(['op-1', 'op-2']) - expect(seen[0]!.frame.seq).toBe(1) - expect(seen[0]!.stagedNodes).toEqual({ '1': { type: 'Source' } }) + expect(seen[0].frame.actor).toBe('agent:planner') + expect(seen[0].frame.opIds).toEqual(['op-1', 'op-2']) + expect(seen[0].frame.seq).toBe(1) + expect(seen[0].stagedNodes).toEqual({ '1': { type: 'Source' } }) }) it('preserves node incarnation bytes through the staged commit path', () => { diff --git a/src/core/graph/document/detachedTargetSession.ts b/src/core/graph/document/detachedTargetSession.ts index 670689f99ef..8b06419c820 100644 --- a/src/core/graph/document/detachedTargetSession.ts +++ b/src/core/graph/document/detachedTargetSession.ts @@ -1,5 +1,6 @@ import * as Y from 'yjs' +import { assert } from '@/base/assert' import { createUuidv4 } from '@/utils/uuid' /** @@ -97,18 +98,15 @@ export function createDetachedTargetSession( let queue: TargetFrame[] = [] let destroyed = false - function assertTarget(frameWorkflowId: string): void { - if (frameWorkflowId !== workflowId) { - throw new Error( - `DetachedTargetSession(${workflowId}) received a frame addressed to ` + - `"${frameWorkflowId}"; frames must never cross targets` - ) - } + function isTarget(frameWorkflowId: string): boolean { + const matchesTarget = frameWorkflowId === workflowId + assert(matchesTarget, 'Detached target frames must never cross targets') + return matchesTarget } function enqueue(frame: TargetFrame): EnqueueResult { if (destroyed) return { status: 'resync-required' } - assertTarget(frame.workflowId) + if (!isTarget(frame.workflowId)) return { status: 'resync-required' } if (needsResync) return { status: 'resync-required' } const lastAcceptedSeq = queue.at(-1)?.seq ?? committedSeq diff --git a/src/core/graph/document/documentSerializer.test.ts b/src/core/graph/document/documentSerializer.test.ts index 5bf7f4eec92..ad0d59a3193 100644 --- a/src/core/graph/document/documentSerializer.test.ts +++ b/src/core/graph/document/documentSerializer.test.ts @@ -92,12 +92,12 @@ describe('serializeDocumentScope', () => { _widget: cyclicWidget as never, hasErrors: true, boundingRect: [0, 0, 10, 10] - } as Partial), + }), output: outputSlot({ links: [toLinkId(5)], _data: { transient: true }, slot_index: 0 - } as Partial) + }) }) const decoded = decode(serializeDocumentScope(scope)) @@ -128,11 +128,11 @@ describe('serializeDocumentScope', () => { input: inputSlot({ link: toLinkId(7), hasErrors: true - } as Partial), + }), output: outputSlot({ links: [toLinkId(7)], _data: 'runtime' - } as Partial) + }) }) expect(serializeDocumentScope(clean)).toEqual(serializeDocumentScope(dirty)) diff --git a/src/core/graph/document/documentSerializer.ts b/src/core/graph/document/documentSerializer.ts index 47498018f87..86948fc69ae 100644 --- a/src/core/graph/document/documentSerializer.ts +++ b/src/core/graph/document/documentSerializer.ts @@ -2,6 +2,7 @@ import type { INodeInputSlot, INodeOutputSlot } from '@/lib/litegraph/src/interfaces' +import { assert } from '@/base/assert' import { useLinkStore } from '@/stores/linkStore' import { useNodeDataStore } from '@/stores/nodeDataStore' import { useWidgetValueStore } from '@/stores/widgetValueStore' @@ -19,9 +20,11 @@ const MAX_CANONICALIZE_DEPTH = 32 function canonicalize(value: unknown, depth = 0): unknown { if (depth > MAX_CANONICALIZE_DEPTH) { - throw new Error( - `serializeDocumentScope: exceeded max canonicalization depth of ${MAX_CANONICALIZE_DEPTH}; semantic state likely contains a cycle or runtime-only object` + assert( + false, + 'serializeDocumentScope: exceeded max canonicalization depth; semantic state likely contains a cycle or runtime-only object' ) + return undefined } if (Array.isArray(value)) return value.map((entry) => canonicalize(entry, depth + 1)) diff --git a/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts b/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts index 3d4931ff706..7df7b0a48d7 100644 --- a/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts +++ b/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts @@ -269,7 +269,7 @@ describe('document activation persistence (ADR-0024 seam)', () => { expect(target?.scope).toEqual(scopeB) expect(target?.documentId).not.toBe(coordinator.activeDocumentId()) - const hostB = mint({ nodes: [workflowJson.nodes[1]!], links: [] }, catalog) + const hostB = mint({ nodes: [workflowJson.nodes[1]], links: [] }, catalog) const sessionB = createDetachedTargetSession('wf-b') commitHostState(sessionB, 'wf-b', hostB, mutationsB) @@ -341,7 +341,7 @@ describe('document activation persistence (ADR-0024 seam)', () => { expect(session.snapshot().lineage).not.toBe(oldLineage) const remintedHost = mint( - { nodes: [workflowJson.nodes[0]!], links: [] }, + { nodes: [workflowJson.nodes[0]], links: [] }, catalog ) commitHostState(session, 'wf', remintedHost, mutations, 11) From 3a70e38c99411293c45abb7f24493c50c383b1d3 Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 3 Sep 2026 23:09:24 +0000 Subject: [PATCH 23/37] fix: preserve hard failures for document invariants Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3929255622 --- src/core/graph/document/detachedTargetSession.test.ts | 3 ++- src/core/graph/document/detachedTargetSession.ts | 4 +++- src/core/graph/document/documentSerializer.test.ts | 3 ++- src/core/graph/document/documentSerializer.ts | 9 ++++----- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/core/graph/document/detachedTargetSession.test.ts b/src/core/graph/document/detachedTargetSession.test.ts index 306200465c3..3d76183ef95 100644 --- a/src/core/graph/document/detachedTargetSession.test.ts +++ b/src/core/graph/document/detachedTargetSession.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import * as Y from 'yjs' import type { @@ -378,6 +378,7 @@ describe('createDetachedTargetSession', () => { }) it('rejects frames addressed to another target loudly', () => { + vi.stubEnv('DEV', false) const session = createDetachedTargetSession(WORKFLOW_ID) const stranger = createFrameSource('wf-other') diff --git a/src/core/graph/document/detachedTargetSession.ts b/src/core/graph/document/detachedTargetSession.ts index 8b06419c820..9007b3f02df 100644 --- a/src/core/graph/document/detachedTargetSession.ts +++ b/src/core/graph/document/detachedTargetSession.ts @@ -60,6 +60,7 @@ export interface DetachedTargetSessionOptions { } const DEFAULT_MAX_QUEUED_FRAMES = 64 +const CROSS_TARGET_ERROR = 'Detached target frames must never cross targets' /** * Staged frame queue for a target document that is not attached to a live @@ -100,7 +101,8 @@ export function createDetachedTargetSession( function isTarget(frameWorkflowId: string): boolean { const matchesTarget = frameWorkflowId === workflowId - assert(matchesTarget, 'Detached target frames must never cross targets') + assert(matchesTarget, CROSS_TARGET_ERROR) + if (!matchesTarget) throw new TypeError(CROSS_TARGET_ERROR) return matchesTarget } diff --git a/src/core/graph/document/documentSerializer.test.ts b/src/core/graph/document/documentSerializer.test.ts index ad0d59a3193..3d368237a40 100644 --- a/src/core/graph/document/documentSerializer.test.ts +++ b/src/core/graph/document/documentSerializer.test.ts @@ -1,6 +1,6 @@ import { createTestingPinia } from '@pinia/testing' import { setActivePinia } from 'pinia' -import { beforeEach, describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { serializeDocumentScope } from '@/core/graph/document/documentSerializer' import type { @@ -164,6 +164,7 @@ describe('serializeDocumentScope', () => { }) it('throws on pathologically deep semantic state instead of hanging', () => { + vi.stubEnv('DEV', false) const scope = scopeFor('root-deep') let deep: unknown = 0 for (let i = 0; i < 40; i++) deep = [deep] diff --git a/src/core/graph/document/documentSerializer.ts b/src/core/graph/document/documentSerializer.ts index 86948fc69ae..47f5320a81a 100644 --- a/src/core/graph/document/documentSerializer.ts +++ b/src/core/graph/document/documentSerializer.ts @@ -10,6 +10,8 @@ import type { GraphScope } from '@/types/graphScopeId' import { compareNodeIds } from '@/types/nodeId' const RENDER_ONLY_KEYS = new Set(['boundingRect']) +const MAX_DEPTH_ERROR = + 'serializeDocumentScope: exceeded max canonicalization depth; semantic state likely contains a cycle or runtime-only object' /** * Safety net against unbounded or cyclic structures reaching the @@ -20,11 +22,8 @@ const MAX_CANONICALIZE_DEPTH = 32 function canonicalize(value: unknown, depth = 0): unknown { if (depth > MAX_CANONICALIZE_DEPTH) { - assert( - false, - 'serializeDocumentScope: exceeded max canonicalization depth; semantic state likely contains a cycle or runtime-only object' - ) - return undefined + assert(false, MAX_DEPTH_ERROR) + throw new TypeError(MAX_DEPTH_ERROR) } if (Array.isArray(value)) return value.map((entry) => canonicalize(entry, depth + 1)) From 1309936f12bd2f04f057b372249e649a55727b91 Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 4 Sep 2026 07:24:54 +0000 Subject: [PATCH 24/37] fix: address graph document lifecycle review feedback --- .../document/activationCoordinator.test.ts | 17 +- .../graph/document/activationCoordinator.ts | 22 +- .../document/detachedTargetSession.test.ts | 10 + .../graph/document/detachedTargetSession.ts | 1 + .../management/stores/comfyWorkflow.test.ts | 270 +++++++++--------- .../management/stores/comfyWorkflow.ts | 22 +- src/stores/graphDocumentStore.test.ts | 6 + 7 files changed, 200 insertions(+), 148 deletions(-) diff --git a/src/core/graph/document/activationCoordinator.test.ts b/src/core/graph/document/activationCoordinator.test.ts index 544c31ea50e..dacfb0f6645 100644 --- a/src/core/graph/document/activationCoordinator.test.ts +++ b/src/core/graph/document/activationCoordinator.test.ts @@ -1,13 +1,16 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import type { ActivationOutcome, DocumentViewBinding } from '@/core/graph/document/activationCoordinator' import { createActivationCoordinator } from '@/core/graph/document/activationCoordinator' +import { reportError } from '@/platform/telemetry/reportError' import type { DocumentId } from '@/types/documentId' import { toDocumentId } from '@/types/documentId' +vi.mock('@/platform/telemetry/reportError', () => ({ reportError: vi.fn() })) + function recordingBinding(log: string[], name: string): DocumentViewBinding { return { attach: (id: DocumentId) => log.push(`attach:${name}:${id}`), @@ -72,6 +75,9 @@ describe('createActivationCoordinator', () => { }) expect(coordinator.activeDocumentId()).toBe(docA) expect(log).toEqual([`attach:a:${docA}`]) + expect(reportError).toHaveBeenCalledWith(expect.any(Error), { + errorType: 'document_activation_hydration_failure' + }) }) it('performs an ordered detach-then-attach handoff between documents', async () => { @@ -206,6 +212,9 @@ describe('createActivationCoordinator', () => { `detach:a:${docA}`, `detach:b:${docB}` ]) + expect(reportError).toHaveBeenCalledWith(expect.any(Error), { + errorType: 'document_view_binding_attach_failure' + }) }) it('a reentrant deactivate from within attach supersedes the activation', async () => { @@ -300,6 +309,9 @@ describe('createActivationCoordinator', () => { reason: 'handoff-failed' }) expect(coordinator.activeDocumentId()).toBeNull() + expect(reportError).toHaveBeenCalledWith(expect.any(Error), { + errorType: 'document_view_binding_previous_detach_failure' + }) // A follow-up activate succeeds without re-detaching the failed binding. const retry = await coordinator.activate(docB, recordingBinding(log, 'b')) @@ -330,5 +342,8 @@ describe('createActivationCoordinator', () => { expect(coordinator.deactivate(docA)).toBe(true) expect(coordinator.activeDocumentId()).toBeNull() + expect(reportError).toHaveBeenCalledWith(expect.any(Error), { + errorType: 'document_view_binding_detach_failure' + }) }) }) diff --git a/src/core/graph/document/activationCoordinator.ts b/src/core/graph/document/activationCoordinator.ts index 7b2edebff09..ab9902b7ca5 100644 --- a/src/core/graph/document/activationCoordinator.ts +++ b/src/core/graph/document/activationCoordinator.ts @@ -1,4 +1,5 @@ import type { DocumentId } from '@/types/documentId' +import { reportError } from '@/platform/telemetry/reportError' /** * View concerns attached by activation and detached by deactivation: the @@ -66,7 +67,10 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { } try { await deps.hydrate?.(documentId) - } catch { + } catch (error) { + reportError(error, { + errorType: 'document_activation_hydration_failure' + }) return finish( stale() ? { status: 'superseded', documentId } @@ -81,7 +85,10 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { active = null try { if (previous) previous.binding.detach(previous.documentId) - } catch { + } catch (error) { + reportError(error, { + errorType: 'document_view_binding_previous_detach_failure' + }) // A throwing detach must not leave a stale published binding: a later // activate/deactivate would detach the old document twice. return finish({ @@ -96,7 +103,10 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { if (stale()) return finish({ status: 'superseded', documentId }) try { binding.attach(documentId) - } catch { + } catch (error) { + reportError(error, { + errorType: 'document_view_binding_attach_failure' + }) // Best-effort cleanup of hooks a partially-run attach installed; the // binding stays unpublished either way. try { @@ -146,8 +156,10 @@ export function createActivationCoordinator(deps: ActivationCoordinatorDeps) { active = null try { previous.binding.detach(documentId) - } catch { - /* treated as detached (DocumentViewBinding contract) */ + } catch (error) { + reportError(error, { + errorType: 'document_view_binding_detach_failure' + }) } return true } diff --git a/src/core/graph/document/detachedTargetSession.test.ts b/src/core/graph/document/detachedTargetSession.test.ts index 3d76183ef95..3d7d99a5ef8 100644 --- a/src/core/graph/document/detachedTargetSession.test.ts +++ b/src/core/graph/document/detachedTargetSession.test.ts @@ -377,6 +377,16 @@ describe('createDetachedTargetSession', () => { expect(session.snapshot().needsResync).toBe(true) }) + it('does not recreate lineage state after destruction', () => { + const session = createDetachedTargetSession(WORKFLOW_ID) + const beforeDestroy = session.snapshot() + + session.destroy() + session.resetLineage(10) + + expect(session.snapshot()).toEqual(beforeDestroy) + }) + it('rejects frames addressed to another target loudly', () => { vi.stubEnv('DEV', false) const session = createDetachedTargetSession(WORKFLOW_ID) diff --git a/src/core/graph/document/detachedTargetSession.ts b/src/core/graph/document/detachedTargetSession.ts index 9007b3f02df..ae9593d04ca 100644 --- a/src/core/graph/document/detachedTargetSession.ts +++ b/src/core/graph/document/detachedTargetSession.ts @@ -205,6 +205,7 @@ export function createDetachedTargetSession( * frames from the old lineage are meaningless and dropped. */ function resetLineage(atSeq: number): void { + if (destroyed) return committedDoc.destroy() committedDoc = new Y.Doc() lineage = createUuidv4() diff --git a/src/platform/workflow/management/stores/comfyWorkflow.test.ts b/src/platform/workflow/management/stores/comfyWorkflow.test.ts index 33af00dee4a..0e743cce0fb 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.test.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.test.ts @@ -5,6 +5,16 @@ import { useWorkflowStore } from '@/platform/workflow/management/stores/workflow import { api } from '@/scripts/api' import { useGraphDocumentStore } from '@/stores/graphDocumentStore' +interface WorkflowDraft { + data: string + updatedAt: number +} + +const { getDraft, getSetting } = vi.hoisted(() => ({ + getDraft: vi.fn<() => WorkflowDraft | undefined>(() => undefined), + getSetting: vi.fn<() => boolean>(() => false) +})) + vi.mock('@/scripts/api', () => ({ api: { getUserData: vi.fn(), @@ -15,7 +25,7 @@ vi.mock('@/scripts/api', () => ({ vi.mock('@/platform/workflow/persistence/stores/workflowDraftStoreV2', () => ({ useWorkflowDraftStoreV2: vi.fn(() => ({ - getDraft: vi.fn(() => undefined), + getDraft, markDraftUsed: vi.fn(), removeDraft: vi.fn() })) @@ -23,7 +33,7 @@ vi.mock('@/platform/workflow/persistence/stores/workflowDraftStoreV2', () => ({ vi.mock('@/platform/settings/settingStore', () => ({ useSettingStore: vi.fn(() => ({ - get: vi.fn(() => false) + get: getSetting })) })) @@ -58,6 +68,8 @@ vi.mock('@/stores/subgraphNavigationStore', () => ({ })) })) +await import('@/scripts/changeTracker') + function mockLoadResponse(content: string) { vi.mocked(api.getUserData).mockResolvedValue({ status: 200, @@ -78,140 +90,124 @@ async function createLoadedWorkflow(path = 'workflows/test.json') { return workflow } -// `load()`'s dynamic `import('@/scripts/changeTracker')` pulls in the -// litegraph module graph; vitest's on-demand transform of that graph is slow -// (not hung) the first time it runs inside a test body rather than at static -// import/collection time, so these tests need a generous timeout. -const LOAD_TIMEOUT = 30_000 - describe('ComfyWorkflow document identity (ADR-0024)', () => { - it( - 'mints a local-only document id on load', - async () => { - const workflow = await createLoadedWorkflow() - expect(workflow.documentId).not.toBeNull() - - const store = useGraphDocumentStore() - const entry = store.getDocument(workflow.documentId!) - expect(entry).not.toBeNull() - expect(entry?.workflowId).toBeNull() - expect(store.persistenceStateOf(workflow.documentId!)).toBe('unsaved') - }, - LOAD_TIMEOUT - ) - - it( - 'reuses the same document id across a re-entrant load', - async () => { - const workflow = await createLoadedWorkflow() - const firstId = workflow.documentId - mockLoadResponse(JSON.stringify({ nodes: [], links: [] })) - await workflow.load({ force: true }) - expect(workflow.documentId).toBe(firstId) - }, - LOAD_TIMEOUT - ) - - it( - 'keeps the same document id across unload (no closer exists yet)', - async () => { - const workflow = await createLoadedWorkflow() - const firstId = workflow.documentId - workflow.unload() - // unload() does not clear documentId — the registry entry for the old - // load is left standing until an explicit close, matching the - // create-on-load/no-close-yet lifecycle documented on the field. - expect(workflow.documentId).toBe(firstId) - }, - LOAD_TIMEOUT - ) - - it( - 'advances the document from unsaved to clean at the exact saved revision', - async () => { - const workflow = await createLoadedWorkflow() - const store = useGraphDocumentStore() - const documentId = workflow.documentId! - expect(store.persistenceStateOf(documentId)).toBe('unsaved') - - mockSaveResponse() - await workflow.save() - - expect(store.persistenceStateOf(documentId)).toBe('clean') - }, - LOAD_TIMEOUT - ) - - it( - 'reports dirty for a mutation committed after the last save', - async () => { - const workflow = await createLoadedWorkflow() - const store = useGraphDocumentStore() - const documentId = workflow.documentId! - - mockSaveResponse() - await workflow.save() - expect(store.persistenceStateOf(documentId)).toBe('clean') - - store.markMutated(documentId) - expect(store.persistenceStateOf(documentId)).toBe('dirty') - }, - LOAD_TIMEOUT - ) - - it( - 'leaves the document dirty when a mutation commits mid-save', - async () => { - const workflow = await createLoadedWorkflow() - useWorkflowStore().attachWorkflow(workflow) - const store = useGraphDocumentStore() - const documentId = workflow.documentId! - - // Establish a saved baseline first so a later revision divergence can - // actually be observed as 'dirty' rather than 'unsaved'. - mockSaveResponse() - await workflow.save() - - // storeUserData resolves only after a mutation commits against the - // same document, simulating a concurrent edit racing the in-flight - // save. - let resolveSave!: (value: { json: () => Promise }) => void - vi.mocked(api.storeUserData).mockReturnValue( - new Promise((resolve) => { - resolveSave = resolve - }) as never - ) - - const savePromise = workflow.save() - const previousState = workflow.changeTracker!.activeState - workflow.changeTracker!.activeState = { - ...previousState, - nodes: [ - { - id: 1, - type: 'KSampler', - pos: [0, 0], - size: [100, 100], - flags: {}, - order: 0, - mode: 0, - inputs: [], - outputs: [], - properties: {} - } - ] - } - workflow.changeTracker!.updateModified(previousState) - resolveSave({ json: () => Promise.resolve('workflows/test.json') }) - await savePromise - - expect(api.storeUserData).toHaveBeenCalledWith( - workflow.path, - JSON.stringify(previousState), - expect.anything() - ) - expect(store.persistenceStateOf(documentId)).toBe('dirty') - }, - LOAD_TIMEOUT - ) + it('mints a clean local-only document id for persisted content', async () => { + const workflow = await createLoadedWorkflow() + expect(workflow.documentId).not.toBeNull() + + const store = useGraphDocumentStore() + const entry = store.getDocument(workflow.documentId!) + expect(entry).not.toBeNull() + expect(entry?.workflowId).toBeNull() + expect(store.persistenceStateOf(workflow.documentId!)).toBe('clean') + }) + + it('reuses the same document id across a re-entrant load', async () => { + const workflow = await createLoadedWorkflow() + const firstId = workflow.documentId + mockLoadResponse(JSON.stringify({ nodes: [], links: [] })) + await workflow.load({ force: true }) + expect(workflow.documentId).toBe(firstId) + }) + + it('keeps the same document id across unload (no closer exists yet)', async () => { + const workflow = await createLoadedWorkflow() + const firstId = workflow.documentId + workflow.unload() + // unload() does not clear documentId — the registry entry for the old + // load is left standing until an explicit close, matching the + // create-on-load/no-close-yet lifecycle documented on the field. + expect(workflow.documentId).toBe(firstId) + }) + + it('marks a restored draft dirty against the persisted baseline', async () => { + const draftState = { nodes: [], links: [], version: 1 } + getSetting.mockReturnValueOnce(true) + getDraft.mockReturnValueOnce({ + data: JSON.stringify(draftState), + updatedAt: 1 + }) + + const workflow = await createLoadedWorkflow() + const store = useGraphDocumentStore() + + expect(store.persistenceStateOf(workflow.documentId!)).toBe('dirty') + }) + + it('keeps the persisted document clean when saving its current revision', async () => { + const workflow = await createLoadedWorkflow() + const store = useGraphDocumentStore() + const documentId = workflow.documentId! + expect(store.persistenceStateOf(documentId)).toBe('clean') + + mockSaveResponse() + await workflow.save() + + expect(store.persistenceStateOf(documentId)).toBe('clean') + }) + + it('reports dirty for a mutation committed after the last save', async () => { + const workflow = await createLoadedWorkflow() + const store = useGraphDocumentStore() + const documentId = workflow.documentId! + + mockSaveResponse() + await workflow.save() + expect(store.persistenceStateOf(documentId)).toBe('clean') + + store.markMutated(documentId) + expect(store.persistenceStateOf(documentId)).toBe('dirty') + }) + + it('leaves the document dirty when a mutation commits mid-save', async () => { + const workflow = await createLoadedWorkflow() + useWorkflowStore().attachWorkflow(workflow) + const store = useGraphDocumentStore() + const documentId = workflow.documentId! + + // Establish a saved baseline first so a later revision divergence can + // actually be observed as 'dirty' rather than 'unsaved'. + mockSaveResponse() + await workflow.save() + + // storeUserData resolves only after a mutation commits against the + // same document, simulating a concurrent edit racing the in-flight + // save. + let resolveSave!: (value: { json: () => Promise }) => void + vi.mocked(api.storeUserData).mockReturnValue( + new Promise((resolve) => { + resolveSave = resolve + }) as never + ) + + const savePromise = workflow.save() + const previousState = workflow.changeTracker!.activeState + workflow.changeTracker!.activeState = { + ...previousState, + nodes: [ + { + id: 1, + type: 'KSampler', + pos: [0, 0], + size: [100, 100], + flags: {}, + order: 0, + mode: 0, + inputs: [], + outputs: [], + properties: {} + } + ] + } + workflow.changeTracker!.updateModified(previousState) + resolveSave({ json: () => Promise.resolve('workflows/test.json') }) + await savePromise + + expect(api.storeUserData).toHaveBeenCalledWith( + workflow.path, + JSON.stringify(previousState), + expect.anything() + ) + expect(store.persistenceStateOf(documentId)).toBe('dirty') + }) }) diff --git a/src/platform/workflow/management/stores/comfyWorkflow.ts b/src/platform/workflow/management/stores/comfyWorkflow.ts index b469e140fce..615f87737fe 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.ts @@ -166,11 +166,21 @@ export class ComfyWorkflow extends UserFile { // `workflow_id` (that mapping is layered on separately, e.g. by the // agent panel). Minted once per load; reused across re-entrant loads of // an already-loaded instance. - this.documentId ??= useGraphDocumentStore().createDocument() + const graphDocumentStore = useGraphDocumentStore() + if (this.documentId === null) { + this.documentId = graphDocumentStore.createDocument() + if (this.documentId !== null) { + const persistedBaseline = graphDocumentStore.beginSave(this.documentId) + if (persistedBaseline) + graphDocumentStore.completeSave(persistedBaseline) + } + } if (draftState && draftContent) { this.changeTracker.activeState = draftState this.content = draftContent this._isModified = true + if (this.documentId !== null) + graphDocumentStore.markMutated(this.documentId) // Saved-workflow draft overlay path; direct persisted-draft restores // are touched in workflowDraftStoreV2.loadDraft(). draftStore.markDraftUsed(this.path) @@ -192,8 +202,10 @@ export class ComfyWorkflow extends UserFile { // invoked — never to whatever revision happens to be current once // control returns to us after yielding. const documentId = this.documentId - const graphDocumentStore = documentId ? useGraphDocumentStore() : null - const saveTicket = graphDocumentStore?.beginSave(documentId!) ?? null + const graphDocumentStore = useGraphDocumentStore() + const saveTicket = documentId + ? graphDocumentStore.beginSave(documentId) + : null const content = JSON.stringify(this.activeState) const { useWorkflowDraftStoreV2 } = @@ -203,10 +215,10 @@ export class ComfyWorkflow extends UserFile { // Force save to ensure the content is updated in remote storage incase // the isModified state is screwed by changeTracker. const ret = await super.save({ force: true }) - if (saveTicket) graphDocumentStore!.completeSave(saveTicket) + if (saveTicket) graphDocumentStore.completeSave(saveTicket) const savedCurrentRevision = saveTicket === null || - graphDocumentStore?.persistenceStateOf(saveTicket.documentId) === 'clean' + graphDocumentStore.persistenceStateOf(saveTicket.documentId) === 'clean' if (savedCurrentRevision) { this.changeTracker?.reset() this.isModified = false diff --git a/src/stores/graphDocumentStore.test.ts b/src/stores/graphDocumentStore.test.ts index 1f27524eac7..1f9b6ba7b97 100644 --- a/src/stores/graphDocumentStore.test.ts +++ b/src/stores/graphDocumentStore.test.ts @@ -139,6 +139,9 @@ describe('useGraphDocumentStore', () => { store.markMutated(documentId) const presentedRevision = store.getDocument(documentId)?.state.revision ?? -1 + const dispose = vi.fn() + const lease = { graph: {}, dispose } + store.completeGraphHydration(store.beginGraphHydration(documentId)!, lease) store.markMutated(documentId) expect( store.closeDocument(documentId, { @@ -147,12 +150,15 @@ describe('useGraphDocumentStore', () => { }) ).toBe(false) expect(store.getDocument(documentId)?.state.phase).toBe('loaded') + expect(store.graphLeaseOf(documentId)).toBe(lease) + expect(dispose).not.toHaveBeenCalled() expect( store.closeDocument(documentId, { atRevision: presentedRevision + 1, discardChanges: true }) ).toBe(true) + expect(dispose).toHaveBeenCalledOnce() }) it('refuses to close a dirty document without an explicit discard', () => { From 4463c64babe3d8f8f3f379e72e4a96a046e7e5cb Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Thu, 10 Sep 2026 14:57:09 -0700 Subject: [PATCH 25/37] fix(agent): commit semantic stores and layout atomically A batch that threw part-way through publishing left the ECS holding a graph the document had rejected: node and widget registration ran before the layout port, so a layout failure surfaced as commitNext -> failed while nodeCount and widget values stayed visible. Layout writes are now buffered until every semantic write has landed, and a throw from either side restores the semantic stores from a pre-batch capture and asks the layout owner to put its own state back. The agent's layout port moves next to the layout store it owns so that restore path is testable against the real store. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3938385417 --- src/core/graph/graphMutations.ts | 197 ++++++++++++++-- .../core/layout/agentLayoutPort.test.ts | 66 ++++++ src/renderer/core/layout/agentLayoutPort.ts | 91 ++++++++ .../extensions/agent/AgentPanelRoot.vue | 43 +--- .../targetFrameProjection.atomicity.test.ts | 216 ++++++++++++++++++ 5 files changed, 559 insertions(+), 54 deletions(-) create mode 100644 src/renderer/core/layout/agentLayoutPort.test.ts create mode 100644 src/renderer/core/layout/agentLayoutPort.ts create mode 100644 src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts diff --git a/src/core/graph/graphMutations.ts b/src/core/graph/graphMutations.ts index 64d87fea562..0c7f8045986 100644 --- a/src/core/graph/graphMutations.ts +++ b/src/core/graph/graphMutations.ts @@ -1,3 +1,5 @@ +import { toRaw } from 'vue' + import type { ISerialisableNodeInput, ISerialisableNodeOutput, @@ -40,11 +42,16 @@ interface SemanticNodeLayout { size: { width: number; height: number } } +/** Restores the layout captured before a batch's layout phase began. */ +export interface SemanticLayoutRestore { + restore(context: RemoteMutationContext): void +} + /** * Renderer-owned layout mutation port. Semantic state never imports the * renderer or writes position into the shared follower Y.Doc. */ -interface SemanticLayoutMutationPort { +export interface SemanticLayoutMutationPort { createNode( scope: GraphScope, nodeId: NodeId, @@ -56,6 +63,18 @@ interface SemanticLayoutMutationPort { nodeIds: readonly NodeId[], context: RemoteMutationContext ): void + /** + * Capture the layout owner's own state for `nodeIds` so a batch that throws + * part-way through its layout phase can be put back exactly as it was. + * Rollback is the owner's job: the semantic stores cannot reconstruct + * z-order or visibility from a node payload. A port that returns `null` + * (or omits this) still gets an all-or-nothing semantic commit, and layout + * rollback degrades to deleting whatever the batch created. + */ + captureNodes?( + scope: GraphScope, + nodeIds: readonly NodeId[] + ): SemanticLayoutRestore | null } interface GraphMutationBatch { @@ -147,6 +166,14 @@ type PreparedMutation = } | { kind: 'clearSemanticGraph'; nodeIds: readonly NodeId[] } +/** + * Layout writes are buffered while the semantic stores commit so the renderer + * is never moved ahead of a batch that still has a chance of failing. + */ +type LayoutOp = + | { kind: 'delete'; nodeIds: readonly NodeId[] } + | { kind: 'create'; nodeId: NodeId; layout: SemanticNodeLayout } + function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } @@ -603,7 +630,8 @@ export function createGraphMutations(deps: GraphMutationsDeps): GraphMutations { scope: GraphScope, nodeId: NodeId, removedLinkIds: readonly LinkId[], - context: RemoteMutationContext + context: RemoteMutationContext, + layoutOps: LayoutOp[] ): void { const node = nodeStore .getGraphNodesFor(scope.rootGraphId, scope.owningGraphId) @@ -619,13 +647,14 @@ export function createGraphMutations(deps: GraphMutationsDeps): GraphMutations { } widgetStore.clearNode(scope.rootGraphId, nodeId, context) if (node) nodeStore.deleteNode(scope, node, context) - deps.layout.deleteNodes(scope, [nodeId], context) + layoutOps.push({ kind: 'delete', nodeIds: [nodeId] }) } function commit( scope: GraphScope, prepared: readonly PreparedMutation[], - context: RemoteMutationContext + context: RemoteMutationContext, + layoutOps: LayoutOp[] ): void { for (const mutation of prepared) { switch (mutation.kind) { @@ -666,12 +695,11 @@ export function createGraphMutations(deps: GraphMutationsDeps): GraphMutations { ) } if (!existing) { - deps.layout.createNode( - scope, - mutation.node.state.id, - mutation.node.layout, - context - ) + layoutOps.push({ + kind: 'create', + nodeId: mutation.node.state.id, + layout: mutation.node.layout + }) } break } @@ -765,7 +793,8 @@ export function createGraphMutations(deps: GraphMutationsDeps): GraphMutations { const topology = linkStore.getTopology(scope.rootGraphId, id) if (topology) removeLink(scope, topology, context) } - for (const id of mutation.nodeIds) deleteNode(scope, id, [], context) + for (const id of mutation.nodeIds) + deleteNode(scope, id, [], context, layoutOps) break case 'removeLinks': for (const id of mutation.linkIds) { @@ -774,13 +803,19 @@ export function createGraphMutations(deps: GraphMutationsDeps): GraphMutations { } break case 'deleteNode': - deleteNode(scope, mutation.nodeId, mutation.removedLinkIds, context) + deleteNode( + scope, + mutation.nodeId, + mutation.removedLinkIds, + context, + layoutOps + ) break case 'clearSemanticGraph': for (const nodeId of mutation.nodeIds) { widgetStore.clearNode(scope.rootGraphId, nodeId, context) } - deps.layout.deleteNodes(scope, mutation.nodeIds, context) + layoutOps.push({ kind: 'delete', nodeIds: mutation.nodeIds }) linkStore.clearOwner(scope, context) linkPresentationStore.clearOwner(scope) nodeStore.clearOwner(scope, context) @@ -789,6 +824,140 @@ export function createGraphMutations(deps: GraphMutationsDeps): GraphMutations { } } + /** + * Everything the semantic stores hold for one scope. Node and widget + * identities are kept — callers hold references to them — and only their + * fields are snapshotted, so a restore puts the same objects back carrying + * their pre-batch values. The copies are shallow because every write in + * `commit` replaces a field or a slot entry wholesale; nothing nested is + * edited in place, and a deep clone would choke on the runtime-only values + * a node payload can carry. + */ + function captureSemanticScope(scope: GraphScope) { + const captureNode = (node: NodeState) => ({ + ...toRaw(node), + inputs: [...node.inputs], + outputs: [...node.outputs] + }) + const nodes = nodeStore + .getGraphNodesFor(scope.rootGraphId, scope.owningGraphId) + .map((node) => ({ + ref: node, + contents: captureNode(node), + widgets: widgetStore + .getNodeWidgetIds(scope.rootGraphId, node.id) + .flatMap((id) => { + const state = widgetStore.getWidget(id) + if (!state) return [] + const renderState = widgetStore.getWidgetRenderState(id) + return [ + { + id, + state: { ...toRaw(state) }, + renderState: renderState ? { ...toRaw(renderState) } : {} + } + ] + }) + })) + const links = [...linkStore.graphTopologies(scope)].map((topology) => ({ + ...toRaw(topology) + })) + + return function restore(context: RemoteMutationContext): void { + const occupied = new Set([ + ...nodeStore + .getGraphNodesFor(scope.rootGraphId, scope.owningGraphId) + .map((node) => node.id), + ...nodes.map((captured) => captured.ref.id) + ]) + for (const nodeId of occupied) + widgetStore.clearNode(scope.rootGraphId, nodeId, context) + linkStore.clearOwner(scope, context) + nodeStore.clearOwner(scope, context) + + for (const captured of nodes) { + Object.assign(captured.ref, captured.contents) + nodeStore.registerNode(scope, captured.ref, context) + for (const widget of captured.widgets) + widgetStore.registerWidget( + widget.id, + widget.state, + widget.renderState, + context + ) + } + for (const topology of links) linkStore.registerLink(scope, topology) + } + } + + function flushLayout( + scope: GraphScope, + layoutOps: readonly LayoutOp[], + context: RemoteMutationContext + ): void { + for (const op of layoutOps) { + if (op.kind === 'delete') + deps.layout.deleteNodes(scope, op.nodeIds, context) + else deps.layout.createNode(scope, op.nodeId, op.layout, context) + } + } + + function touchedNodeIds( + prepared: readonly PreparedMutation[] + ): readonly NodeId[] { + return [ + ...new Set( + prepared.flatMap((mutation) => { + switch (mutation.kind) { + case 'addNode': + case 'reconcileNode': + return [mutation.node.state.id] + case 'setWidget': + return [mutation.nodeId] + case 'deleteNode': + return [mutation.nodeId] + case 'removeMissing': + case 'clearSemanticGraph': + return [...mutation.nodeIds] + case 'connect': + return [ + mutation.topology.originNodeId, + mutation.topology.targetNodeId + ] + case 'removeLinks': + return [] + } + }) + ) + ] + } + + /** + * The batch's single publication point: the semantic stores are written + * first and the renderer's layout second, and a throw from either puts both + * back. Without this, a layout port that raises after node and widget + * registration leaves the ECS holding a graph the document never committed. + */ + function commitAtomically( + scope: GraphScope, + prepared: readonly PreparedMutation[], + context: RemoteMutationContext + ): void { + const touched = touchedNodeIds(prepared) + const restoreSemantic = captureSemanticScope(scope) + const restoreLayout = deps.layout.captureNodes?.(scope, touched) ?? null + const layoutOps: LayoutOp[] = [] + try { + commit(scope, prepared, context, layoutOps) + flushLayout(scope, layoutOps, context) + } catch (error) { + if (restoreLayout) restoreLayout.restore(context) + else deps.layout.deleteNodes(scope, touched, context) + restoreSemantic(context) + throw error + } + } + const graphMutations: GraphMutations = { batch(context, define) { const scope = deps.getScope() @@ -826,7 +995,7 @@ export function createGraphMutations(deps: GraphMutationsDeps): GraphMutations { }) const prepared = prepare(scope, queued) if (typeof prepared === 'string') return fail(prepared) - commit(scope, prepared, context) + commitAtomically(scope, prepared, context) return true }, addNode(payload, context) { diff --git a/src/renderer/core/layout/agentLayoutPort.test.ts b/src/renderer/core/layout/agentLayoutPort.test.ts new file mode 100644 index 00000000000..3184e426f37 --- /dev/null +++ b/src/renderer/core/layout/agentLayoutPort.test.ts @@ -0,0 +1,66 @@ +import { beforeEach, describe, expect, it } from 'vitest' + +import { layoutStore } from '@/renderer/core/layout/store/layoutStore' +import type { RemoteMutationContext } from '@/types/graphMutationContext' +import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' +import { toNodeId } from '@/types/nodeId' +import { createAgentLayoutPort } from '@/renderer/core/layout/agentLayoutPort' + +const scope = { + rootGraphId: toRootGraphId('11111111-1111-4111-8111-111111111111'), + owningGraphId: toOwningGraphId('11111111-1111-4111-8111-111111111111') +} +const context: RemoteMutationContext = { + source: 'agent-remote', + actor: 'agent:test', + opId: 'op-1' +} +const nodeA = toNodeId(1) +const nodeB = toNodeId(2) + +function layoutOf(nodeId: ReturnType) { + const layout = layoutStore.getNodeLayout(scope.rootGraphId, nodeId) + return layout && { position: layout.position, zIndex: layout.zIndex } +} + +describe('createAgentLayoutPort', () => { + const port = createAgentLayoutPort(layoutStore) + + beforeEach(() => { + port.deleteNodes(scope, [nodeA, nodeB], context) + }) + + it('restores a replaced layout, which a bare create cannot', () => { + port.createNode( + scope, + nodeA, + { position: { x: 10, y: 20 }, size: { width: 200, height: 100 } }, + context + ) + const original = layoutOf(nodeA) + + const { captureNodes } = port + if (!captureNodes) throw new Error('the agent layout port must capture') + const capture = captureNodes(scope, [nodeA, nodeB]) + if (!capture) throw new Error('the agent layout port must capture') + port.deleteNodes(scope, [nodeA], context) + port.createNode( + scope, + nodeA, + { position: { x: 900, y: 900 }, size: { width: 10, height: 10 } }, + context + ) + port.createNode( + scope, + nodeB, + { position: { x: 5, y: 5 }, size: { width: 10, height: 10 } }, + context + ) + expect(layoutOf(nodeA)).not.toEqual(original) + + capture.restore(context) + + expect(layoutOf(nodeA)).toEqual(original) + expect(layoutOf(nodeB)).toBeNull() + }) +}) diff --git a/src/renderer/core/layout/agentLayoutPort.ts b/src/renderer/core/layout/agentLayoutPort.ts new file mode 100644 index 00000000000..50d4fb198c6 --- /dev/null +++ b/src/renderer/core/layout/agentLayoutPort.ts @@ -0,0 +1,91 @@ +import type { SemanticLayoutMutationPort } from '@/core/graph/graphMutations' +import type { layoutStore as LayoutStore } from './store/layoutStore' +import { LayoutSource } from './types' + +/** + * The agent's renderer-owned layout port (ADR-GRAPH-DOCUMENT-0024). Layout is + * the one part of a graph mutation the semantic stores cannot reconstruct, so + * this port also supplies the capture the canonical commit rolls back to when + * a batch fails part-way through publishing. + */ +export function createAgentLayoutPort( + layout: typeof LayoutStore +): SemanticLayoutMutationPort { + return { + createNode(scope, nodeId, nodeLayout, context) { + const { position, size } = nodeLayout + layout.applyOperation({ + type: 'createNode', + graphId: scope.rootGraphId, + ownerGraphId: scope.owningGraphId, + nodeId, + layout: { + id: nodeId, + position, + size, + bounds: { x: position.x, y: position.y, ...size }, + zIndex: layout.allocateZIndex(), + visible: true + }, + source: LayoutSource.AgentRemote, + actor: context.actor, + opId: context.opId, + timestamp: Date.now() + }) + }, + deleteNodes(scope, nodeIds, context) { + const timestamp = Date.now() + layout.applyOperations( + nodeIds.map((nodeId) => ({ + type: 'deleteNode', + graphId: scope.rootGraphId, + ownerGraphId: scope.owningGraphId, + nodeId, + source: LayoutSource.AgentRemote, + actor: context.actor, + opId: context.opId, + timestamp + })) + ) + }, + captureNodes(scope, nodeIds) { + const captured = nodeIds.map( + (nodeId) => + [nodeId, layout.getNodeLayout(scope.rootGraphId, nodeId)] as const + ) + return { + restore(context) { + const common = { + graphId: scope.rootGraphId, + ownerGraphId: scope.owningGraphId, + source: LayoutSource.AgentRemote, + actor: context.actor, + opId: context.opId, + timestamp: Date.now() + } + // `createNode` refuses an occupied key, so every captured node is + // cleared before the ones that had a layout are put back. + layout.applyOperations([ + ...captured.map(([nodeId]) => ({ + type: 'deleteNode' as const, + nodeId, + ...common + })), + ...captured.flatMap(([nodeId, nodeLayout]) => + nodeLayout + ? [ + { + type: 'createNode' as const, + nodeId, + layout: { ...nodeLayout }, + ...common + } + ] + : [] + ) + ]) + } + } + } + } +} diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 97e470d9083..a4e8f4f9bb0 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -41,11 +41,11 @@ import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' // The composition root injects the renderer-owned layout port; follower core // stays independent of renderer and LiteGraph runtime values. // eslint-disable-next-line import-x/no-restricted-paths +import { createAgentLayoutPort } from '@/renderer/core/layout/agentLayoutPort' +// eslint-disable-next-line import-x/no-restricted-paths import { layoutStore } from '@/renderer/core/layout/store/layoutStore' // eslint-disable-next-line import-x/no-restricted-paths import { ACTOR_CONFIG } from '@/renderer/core/layout/constants' -// eslint-disable-next-line import-x/no-restricted-paths -import { LayoutSource } from '@/renderer/core/layout/types' import { api } from '@/scripts/api' import { app } from '@/scripts/app' import { useAgentNodeSelectionStore } from '@/stores/agentNodeSelectionStore' @@ -234,44 +234,7 @@ const graphMutations = (workflowId: string) => { } return scope }, - layout: { - createNode(scope, nodeId, layout, context) { - const { position, size } = layout - layoutStore.applyOperation({ - type: 'createNode', - graphId: scope.rootGraphId, - ownerGraphId: scope.owningGraphId, - nodeId, - layout: { - id: nodeId, - position, - size, - bounds: { x: position.x, y: position.y, ...size }, - zIndex: layoutStore.allocateZIndex(), - visible: true - }, - source: LayoutSource.AgentRemote, - actor: context.actor, - opId: context.opId, - timestamp: Date.now() - }) - }, - deleteNodes(scope, nodeIds, context) { - const timestamp = Date.now() - layoutStore.applyOperations( - nodeIds.map((nodeId) => ({ - type: 'deleteNode', - graphId: scope.rootGraphId, - ownerGraphId: scope.owningGraphId, - nodeId, - source: LayoutSource.AgentRemote, - actor: context.actor, - opId: context.opId, - timestamp - })) - ) - } - } + layout: createAgentLayoutPort(layoutStore) }) const tracked = withMutationTracking(mutations, workflowId) graphMutationsByWorkflow.set(workflowId, tracked) diff --git a/src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts b/src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts new file mode 100644 index 00000000000..e04af252e0d --- /dev/null +++ b/src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts @@ -0,0 +1,216 @@ +import { createTestingPinia } from '@pinia/testing' +import { setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it } from 'vitest' +import * as Y from 'yjs' + +import { createDetachedTargetSession } from '@/core/graph/document/detachedTargetSession' +import { createGraphMutations } from '@/core/graph/graphMutations' +import type { SemanticLayoutMutationPort } from '@/core/graph/graphMutations' +import { useLinkStore } from '@/stores/linkStore' +import { useNodeDataStore } from '@/stores/nodeDataStore' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' +import type { NodeId } from '@/types/nodeId' +import { toNodeId } from '@/types/nodeId' +import { widgetId } from '@/types/widgetId' +import { createTargetFrameApplyPort } from '@/workbench/extensions/agent/crdt/targetFrameProjection' + +const scope = { + rootGraphId: toRootGraphId('root'), + owningGraphId: toOwningGraphId('root') +} +const workflowId = 'wf-atomic' + +interface StoredLayout { + position: { x: number; y: number } + size: { width: number; height: number } +} + +/** + * Stands in for the renderer's layout store: it owns real state, so a rolled + * back commit has to put that state back rather than merely skip a spy call. + */ +function layoutOwner(refusedNodeId: () => NodeId | null) { + const layouts = new Map() + const port: SemanticLayoutMutationPort = { + createNode(_scope, nodeId, layout) { + if (refusedNodeId() === nodeId) + throw new Error(`layout port refused ${String(nodeId)}`) + layouts.set(nodeId, structuredClone(layout)) + }, + deleteNodes(_scope, nodeIds) { + for (const nodeId of nodeIds) layouts.delete(nodeId) + }, + captureNodes(_scope, nodeIds) { + const captured = nodeIds.map( + (nodeId) => [nodeId, layouts.get(nodeId)] as const + ) + return { + restore() { + for (const [nodeId, layout] of captured) { + if (layout) layouts.set(nodeId, layout) + else layouts.delete(nodeId) + } + } + } + } + } + return { port, layouts } +} + +/** + * The host's copy of the target document. Frames carry the incremental diff + * between edits, so a later frame genuinely rewrites what an earlier one + * committed instead of losing to it in Yjs conflict resolution. + */ +function targetHost() { + const doc = new Y.Doc() + let delivered = Y.encodeStateVector(doc) + let seq = 0 + return function edit(mutate: (nodes: Y.Map>) => void) { + doc.transact(() => mutate(doc.getMap>('nodes'))) + const update = Y.encodeStateAsUpdate(doc, delivered) + delivered = Y.encodeStateVector(doc) + seq += 1 + return { workflowId, seq, update, actor: 'agent-a' } + } +} + +function putNode( + nodes: Y.Map>, + id: string, + type: string, + seed: number, + x: number +) { + const existing = nodes.get(id) + const node = existing ?? new Y.Map() + if (!existing) nodes.set(id, node) + node.set('type', type) + node.set('pos', [x, 20]) + node.set('size', [200, 100]) + node.set('widgets_values', { seed }) +} + +function ecsSnapshot() { + const nodes = useNodeDataStore().getGraphNodesFor('root', 'root') + const widgetStore = useWidgetValueStore() + return { + nodes: nodes.map((node) => ({ + id: node.id, + type: node.type, + seed: widgetStore.getWidget(widgetId('root', node.id, 'seed'))?.value + })), + links: [...useLinkStore().graphTopologies(scope)].map((link) => link.id) + } +} + +describe('detached target commit atomicity', () => { + beforeEach(() => { + setActivePinia(createTestingPinia({ stubActions: false })) + }) + + it('publishes nothing when a later commit step fails, then retries once', () => { + let refused: NodeId | null = toNodeId(8) + const { port: layout, layouts } = layoutOwner(() => refused) + const session = createDetachedTargetSession(workflowId) + const applyPort = createTargetFrameApplyPort( + createGraphMutations({ getScope: () => scope, layout }) + ) + const edit = targetHost() + + session.enqueue( + edit((nodes) => { + putNode(nodes, '7', 'Type7', 42, 10) + putNode(nodes, '8', 'Type8', 43, 30) + }) + ) + + expect(session.commitNext(applyPort).status).toBe('failed') + expect(ecsSnapshot()).toEqual({ nodes: [], links: [] }) + expect([...layouts.keys()]).toEqual([]) + expect(session.snapshot()).toMatchObject({ + revision: 0, + committedSeq: null, + queuedFrames: 1, + needsResync: false, + lastCommitId: null + }) + + refused = null + + expect(session.commitNext(applyPort).status).toBe('committed') + expect(ecsSnapshot()).toEqual({ + nodes: [ + { id: '7', type: 'Type7', seed: 42 }, + { id: '8', type: 'Type8', seed: 43 } + ], + links: [] + }) + expect( + [...layouts.entries()].map(([id, stored]) => [id, stored.position.x]) + ).toEqual([ + [toNodeId(7), 10], + [toNodeId(8), 30] + ]) + expect(session.snapshot()).toMatchObject({ + revision: 1, + committedSeq: 1, + queuedFrames: 0 + }) + expect(session.commitNext(applyPort).status).toBe('idle') + }) + + it('rolls the semantic stores back for a port that cannot capture layout', () => { + const { port, layouts } = layoutOwner(() => toNodeId(8)) + const { captureNodes: _unsupported, ...withoutCapture } = port + const session = createDetachedTargetSession(workflowId) + const applyPort = createTargetFrameApplyPort( + createGraphMutations({ getScope: () => scope, layout: withoutCapture }) + ) + const edit = targetHost() + + session.enqueue( + edit((nodes) => { + putNode(nodes, '7', 'Type7', 42, 10) + putNode(nodes, '8', 'Type8', 43, 30) + }) + ) + + expect(session.commitNext(applyPort).status).toBe('failed') + expect(ecsSnapshot()).toEqual({ nodes: [], links: [] }) + expect([...layouts.keys()]).toEqual([]) + }) + + it('keeps the previously committed content when a replacing frame fails', () => { + let refused: NodeId | null = null + const { port: layout, layouts } = layoutOwner(() => refused) + const session = createDetachedTargetSession(workflowId) + const applyPort = createTargetFrameApplyPort( + createGraphMutations({ getScope: () => scope, layout }) + ) + const edit = targetHost() + + session.enqueue(edit((nodes) => putNode(nodes, '7', 'Type7', 42, 10))) + expect(session.commitNext(applyPort).status).toBe('committed') + const committed = ecsSnapshot() + const committedLayouts = JSON.stringify([...layouts.entries()]) + + refused = toNodeId(9) + session.enqueue( + edit((nodes) => { + putNode(nodes, '7', 'Type7Replaced', 99, 500) + putNode(nodes, '9', 'Type9', 7, 700) + }) + ) + + expect(session.commitNext(applyPort).status).toBe('failed') + expect(ecsSnapshot()).toEqual(committed) + expect(JSON.stringify([...layouts.entries()])).toEqual(committedLayouts) + expect(session.snapshot()).toMatchObject({ + revision: 1, + committedSeq: 1, + queuedFrames: 1 + }) + }) +}) From d6199e809cd0f577ae64f7319058aa72953f4401 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Thu, 10 Sep 2026 14:59:51 -0700 Subject: [PATCH 26/37] fix(agent): bind the remote target to the workflow's own document Loading a workflow minted ComfyWorkflow.documentId and established its save baseline; the agent panel independently minted a second document for the same workflow's cloud address, and nothing joined them. A remote write advanced one revision while the local save ticket read the other, so a save could not observe a concurrent remote mutation. The registry now resolves a cloud workflow id onto the document the workflow already owns, giving assignWorkflowId its production caller. A workflow that is not open locally still gets a registry-owned document; an address that would fork identity is refused rather than duplicated. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3938385406 --- src/stores/graphDocumentStore.test.ts | 52 +++++++++++++++++++ src/stores/graphDocumentStore.ts | 21 ++++++++ .../extensions/agent/AgentPanelRoot.vue | 14 +++-- 3 files changed, 82 insertions(+), 5 deletions(-) diff --git a/src/stores/graphDocumentStore.test.ts b/src/stores/graphDocumentStore.test.ts index 1f9b6ba7b97..afe807dc41e 100644 --- a/src/stores/graphDocumentStore.test.ts +++ b/src/stores/graphDocumentStore.test.ts @@ -131,6 +131,58 @@ describe('useGraphDocumentStore', () => { expect(store.persistenceStateOf(documentId)).toBe('clean') }) + it('binds a remote target onto the workflow document that already owns it', () => { + const store = useGraphDocumentStore() + const owned = store.createDocument() + if (owned === null) throw new Error('createDocument failed') + + expect(store.resolveOrBindWorkflowTarget('wf-1', owned)).toBe(owned) + expect(store.resolveWorkflowTarget('wf-1')?.documentId).toBe(owned) + expect(store.resolveOrBindWorkflowTarget('wf-1', owned)).toBe(owned) + }) + + it('mints a target only for a workflow no local document owns', () => { + const store = useGraphDocumentStore() + const minted = store.resolveOrBindWorkflowTarget('wf-1', null) + if (minted === null) throw new Error('bind failed') + + const otherWorkflowDocument = store.createDocument() + if (otherWorkflowDocument === null) throw new Error('createDocument failed') + expect( + store.resolveOrBindWorkflowTarget('wf-1', otherWorkflowDocument) + ).toBe(minted) + expect( + store.resolveOrBindWorkflowTarget('wf-2', otherWorkflowDocument) + ).toBe(otherWorkflowDocument) + }) + + it('refuses to fork identity when the owning document is already addressed', () => { + const store = useGraphDocumentStore() + const owned = store.createDocument({ workflowId: 'wf-1' }) + if (owned === null) throw new Error('createDocument failed') + + expect(store.resolveOrBindWorkflowTarget('wf-2', owned)).toBeNull() + expect(store.resolveWorkflowTarget('wf-2')).toBeNull() + }) + + it('leaves a bound document dirty when a remote commit lands mid-save', () => { + const store = useGraphDocumentStore() + const owned = store.createDocument() + if (owned === null) throw new Error('createDocument failed') + store.hydrateDocument(owned, scope) + expect(store.resolveOrBindWorkflowTarget('wf-1', owned)).toBe(owned) + + const ticket = store.beginSave(owned) + if (!ticket) throw new Error('beginSave failed') + const remoteTarget = store.resolveWorkflowTarget('wf-1')?.documentId + if (!remoteTarget) throw new Error('remote target unresolved') + store.markMutated(remoteTarget) + store.completeSave(ticket) + + expect(remoteTarget).toBe(owned) + expect(store.persistenceStateOf(owned)).toBe('dirty') + }) + it('close is compare-and-set: a stale decision must be re-presented', () => { const store = useGraphDocumentStore() const documentId = store.createDocument() diff --git a/src/stores/graphDocumentStore.ts b/src/stores/graphDocumentStore.ts index 47b47a5ca37..fc323be07df 100644 --- a/src/stores/graphDocumentStore.ts +++ b/src/stores/graphDocumentStore.ts @@ -264,10 +264,31 @@ export const useGraphDocumentStore = defineStore('graphDocument', () => { return true } + /** + * Resolve the document a cloud `workflow_id` addresses, binding the address + * onto the document the workflow lifecycle already owns rather than minting + * a second one. A workflow that is not open locally has no owner to bind to + * and gets a registry-owned document, so remote targets stay addressable. + * Returns `null` when the address cannot be bound — a duplicate or stale + * mapping is refused, never silently forked into a parallel identity. + */ + function resolveOrBindWorkflowTarget( + workflowId: string, + ownedDocumentId: DocumentId | null + ): DocumentId | null { + const mapped = resolveWorkflowTarget(workflowId) + if (mapped) return mapped.documentId + if (ownedDocumentId === null) return createDocument({ workflowId }) + return assignWorkflowId(ownedDocumentId, workflowId) + ? ownedDocumentId + : null + } + return { createDocument, getDocument, resolveWorkflowTarget, + resolveOrBindWorkflowTarget, persistenceStateOf, graphLeaseOf, beginGraphHydration, diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index a4e8f4f9bb0..d942a2f5393 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -166,13 +166,17 @@ const canvasStore = useCanvasStore() const graphDocumentStore = useGraphDocumentStore() const graphMutationsByWorkflow = new Map() /** - * Resolve the live document for a workflow id, creating the registry entry - * when none exists. Never captured: a workflow id can be remapped to a new - * document after the previous one closes, so callers re-resolve per use. + * Resolve the live document for a workflow id. The bound tab's workflow owns + * its document identity, so the cloud address binds onto that document and + * agent writes advance the same revision the local save baseline reads. + * Never captured: a workflow id can be remapped to a new document after the + * previous one closes, so callers re-resolve per use. */ const resolveDocumentId = (workflowId: string) => - graphDocumentStore.resolveWorkflowTarget(workflowId)?.documentId ?? - graphDocumentStore.createDocument({ workflowId }) + graphDocumentStore.resolveOrBindWorkflowTarget( + workflowId, + boundTabFor(workflowId)?.documentId ?? null + ) /** * Record every successful write against the target's document so its * revision advances (ADR-0024 dirty tracking). Each method resolves the From fb2da298531fbf22e4f1f622e64642e0d0beb19f Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Thu, 10 Sep 2026 15:12:41 -0700 Subject: [PATCH 27/37] chore: realign the document seam with main's lint and store contracts Rebase drift only, no behaviour change beyond what the new contracts require: - prefixed ADR identifiers, which adr:check now enforces - global testing pinia and dynamic-import module mocks per the new oxlint rules, with shoehorn fromPartial for the partial app/api stubs - widgetValueStore's added visibility argument, carried through the commit rollback capture so a restore puts visibility back too - linkPresentationStore added to that capture for the same reason - cross-target rejection re-derived from its operands, since assert only throws in DEV and the compiler had narrowed the flag away --- .../document/activationCoordinator.test.ts | 4 +- .../graph/document/activationCoordinator.ts | 4 +- .../graph/document/detachedTargetSession.ts | 20 ++-- src/core/graph/document/documentLifecycle.ts | 2 +- .../graph/document/documentSerializer.test.ts | 8 +- src/core/graph/document/documentSerializer.ts | 2 +- src/core/graph/graphMutations.ts | 17 +++- .../management/stores/comfyWorkflow.test.ts | 93 ++++++------------- .../management/stores/comfyWorkflow.ts | 4 +- src/scripts/changeTracker.ts | 2 +- src/stores/graphDocumentStore.test.ts | 8 +- src/stores/graphDocumentStore.ts | 2 +- src/types/documentId.ts | 2 +- .../extensions/agent/AgentPanelRoot.vue | 4 +- ...tActivationPersistence.integration.test.ts | 10 +- .../targetFrameProjection.atomicity.test.ts | 8 +- .../agent/crdt/targetFrameProjection.ts | 2 +- 17 files changed, 75 insertions(+), 117 deletions(-) diff --git a/src/core/graph/document/activationCoordinator.test.ts b/src/core/graph/document/activationCoordinator.test.ts index dacfb0f6645..acece6d45e1 100644 --- a/src/core/graph/document/activationCoordinator.test.ts +++ b/src/core/graph/document/activationCoordinator.test.ts @@ -9,7 +9,9 @@ import { reportError } from '@/platform/telemetry/reportError' import type { DocumentId } from '@/types/documentId' import { toDocumentId } from '@/types/documentId' -vi.mock('@/platform/telemetry/reportError', () => ({ reportError: vi.fn() })) +vi.mock(import('@/platform/telemetry/reportError'), () => ({ + reportError: vi.fn() +})) function recordingBinding(log: string[], name: string): DocumentViewBinding { return { diff --git a/src/core/graph/document/activationCoordinator.ts b/src/core/graph/document/activationCoordinator.ts index ab9902b7ca5..f5e89d562cb 100644 --- a/src/core/graph/document/activationCoordinator.ts +++ b/src/core/graph/document/activationCoordinator.ts @@ -5,7 +5,7 @@ import { reportError } from '@/platform/telemetry/reportError' * View concerns attached by activation and detached by deactivation: the * renderer/canvas binding, render-attached caches, viewport projection, and * input/event hooks. Attach and detach must not touch semantic document - * state (ADR-0024: activation is presentation). + * state (ADR-GRAPH-DOCUMENT-0024: activation is presentation). * * Contract: the coordinator may call `detach` to undo an `attach` that threw * or was superseded mid-handoff, so `detach` must tolerate a partially @@ -38,7 +38,7 @@ export interface ActivationCoordinatorDeps { } /** - * Serializes document activation onto the active-canvas binding (ADR-0024). + * Serializes document activation onto the active-canvas binding (ADR-GRAPH-DOCUMENT-0024). * Requests carry a monotonic generation: a newer request cancels any older * in-flight one, and a stale request may clean up its private staged work * but can never detach, attach, or publish. The winning request performs one diff --git a/src/core/graph/document/detachedTargetSession.ts b/src/core/graph/document/detachedTargetSession.ts index ae9593d04ca..c1ca6d79707 100644 --- a/src/core/graph/document/detachedTargetSession.ts +++ b/src/core/graph/document/detachedTargetSession.ts @@ -64,7 +64,7 @@ const CROSS_TARGET_ERROR = 'Detached target frames must never cross targets' /** * Staged frame queue for a target document that is not attached to a live - * follower (ADR-0024's unloaded-target path). Frames enqueue in wire order + * follower (ADR-GRAPH-DOCUMENT-0024's unloaded-target path). Frames enqueue in wire order * and commit one at a time: each commit folds the head frame into a clone of * the last committed Yjs state, offers it to the projection port, and only * on success publishes the new committed tuple @@ -99,16 +99,20 @@ export function createDetachedTargetSession( let queue: TargetFrame[] = [] let destroyed = false - function isTarget(frameWorkflowId: string): boolean { - const matchesTarget = frameWorkflowId === workflowId - assert(matchesTarget, CROSS_TARGET_ERROR) - if (!matchesTarget) throw new TypeError(CROSS_TARGET_ERROR) - return matchesTarget + /** + * A frame addressed to another target is a wiring bug, not a recoverable + * transport condition. `assert` reports it but only throws in DEV, so the + * production throw is re-derived from the operands rather than from the + * asserted flag, which the compiler has already narrowed. + */ + function assertTarget(frameWorkflowId: string): void { + assert(frameWorkflowId === workflowId, CROSS_TARGET_ERROR) + if (frameWorkflowId !== workflowId) throw new TypeError(CROSS_TARGET_ERROR) } function enqueue(frame: TargetFrame): EnqueueResult { if (destroyed) return { status: 'resync-required' } - if (!isTarget(frame.workflowId)) return { status: 'resync-required' } + assertTarget(frame.workflowId) if (needsResync) return { status: 'resync-required' } const lastAcceptedSeq = queue.at(-1)?.seq ?? committedSeq @@ -137,7 +141,7 @@ export function createDetachedTargetSession( function commitNext(port: TargetFrameApplyPort): CommitResult { if (destroyed) return { status: 'idle' } if (needsResync) return { status: 'resync-required' } - const frame = queue[0] + const frame = queue.at(0) if (!frame) return { status: 'idle' } const staged = new Y.Doc() diff --git a/src/core/graph/document/documentLifecycle.ts b/src/core/graph/document/documentLifecycle.ts index 733355aa679..6f79e9d1381 100644 --- a/src/core/graph/document/documentLifecycle.ts +++ b/src/core/graph/document/documentLifecycle.ts @@ -1,6 +1,6 @@ /** * The pure lifecycle/persistence transition of one `GraphDocument` - * (ADR-0024). Lifecycle (`created | loaded | closed`) and persistence + * (ADR-GRAPH-DOCUMENT-0024). Lifecycle (`created | loaded | closed`) and persistence * (`unsaved | clean | dirty`) are independent: the first describes document * existence, the second compares the document with its persistence baseline. * Persistence is derived from `revision` vs `savedRevision`, never stored. diff --git a/src/core/graph/document/documentSerializer.test.ts b/src/core/graph/document/documentSerializer.test.ts index 3d368237a40..042094e5000 100644 --- a/src/core/graph/document/documentSerializer.test.ts +++ b/src/core/graph/document/documentSerializer.test.ts @@ -1,6 +1,4 @@ -import { createTestingPinia } from '@pinia/testing' -import { setActivePinia } from 'pinia' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { serializeDocumentScope } from '@/core/graph/document/documentSerializer' import type { @@ -77,10 +75,6 @@ function populateScope( } describe('serializeDocumentScope', () => { - beforeEach(() => { - setActivePinia(createTestingPinia({ stubActions: false })) - }) - it('serializes only allowlisted slot fields, ignoring runtime-only state', () => { // Runtime-only junk, including a cycle through `_widget` — the exact // shape that would explode JSON.stringify if slots were spread as-is. diff --git a/src/core/graph/document/documentSerializer.ts b/src/core/graph/document/documentSerializer.ts index 47f5320a81a..b8d0dc0a126 100644 --- a/src/core/graph/document/documentSerializer.ts +++ b/src/core/graph/document/documentSerializer.ts @@ -76,7 +76,7 @@ function pickSlot(slot: INodeInputSlot | INodeOutputSlot) { /** * Renderer-independent canonical serialization of one document scope's - * semantic ECS state (ADR-0024's persistence seam). Reads only the domain + * semantic ECS state (ADR-GRAPH-DOCUMENT-0024's persistence seam). Reads only the domain * stores — never the canvas, layout, or litegraph instances — so the same * document content produces the same bytes whether the document is active * on the canvas, activated under a different renderer, or never activated diff --git a/src/core/graph/graphMutations.ts b/src/core/graph/graphMutations.ts index 0c7f8045986..428be676d5f 100644 --- a/src/core/graph/graphMutations.ts +++ b/src/core/graph/graphMutations.ts @@ -43,7 +43,7 @@ interface SemanticNodeLayout { } /** Restores the layout captured before a batch's layout phase began. */ -export interface SemanticLayoutRestore { +interface SemanticLayoutRestore { restore(context: RemoteMutationContext): void } @@ -850,17 +850,20 @@ export function createGraphMutations(deps: GraphMutationsDeps): GraphMutations { const state = widgetStore.getWidget(id) if (!state) return [] const renderState = widgetStore.getWidgetRenderState(id) + const visibility = widgetStore.getWidgetVisibility(id) return [ { id, state: { ...toRaw(state) }, - renderState: renderState ? { ...toRaw(renderState) } : {} + renderState: renderState ? { ...toRaw(renderState) } : {}, + visibility: visibility ? { ...toRaw(visibility) } : undefined } ] }) })) const links = [...linkStore.graphTopologies(scope)].map((topology) => ({ - ...toRaw(topology) + topology: { ...toRaw(topology) }, + presentation: linkPresentationStore.getPresentation(scope, topology.id) })) return function restore(context: RemoteMutationContext): void { @@ -872,6 +875,7 @@ export function createGraphMutations(deps: GraphMutationsDeps): GraphMutations { ]) for (const nodeId of occupied) widgetStore.clearNode(scope.rootGraphId, nodeId, context) + linkPresentationStore.clearOwner(scope) linkStore.clearOwner(scope, context) nodeStore.clearOwner(scope, context) @@ -883,10 +887,15 @@ export function createGraphMutations(deps: GraphMutationsDeps): GraphMutations { widget.id, widget.state, widget.renderState, + widget.visibility, context ) } - for (const topology of links) linkStore.registerLink(scope, topology) + for (const { topology, presentation } of links) { + linkStore.registerLink(scope, topology) + if (presentation) + linkPresentationStore.patch(scope, topology.id, presentation) + } } } diff --git a/src/platform/workflow/management/stores/comfyWorkflow.test.ts b/src/platform/workflow/management/stores/comfyWorkflow.test.ts index 0e743cce0fb..e66f0bc9f10 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.test.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.test.ts @@ -3,70 +3,35 @@ import { describe, expect, it, vi } from 'vitest' import { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { api } from '@/scripts/api' +import type { ComfyApi } from '@/scripts/api' +import type { ComfyApp } from '@/scripts/app' +import { useSettingStore } from '@/platform/settings/settingStore' +import { useWorkflowDraftStoreV2 } from '@/platform/workflow/persistence/stores/workflowDraftStoreV2' import { useGraphDocumentStore } from '@/stores/graphDocumentStore' -interface WorkflowDraft { - data: string - updatedAt: number -} - -const { getDraft, getSetting } = vi.hoisted(() => ({ - getDraft: vi.fn<() => WorkflowDraft | undefined>(() => undefined), - getSetting: vi.fn<() => boolean>(() => false) -})) - -vi.mock('@/scripts/api', () => ({ - api: { - getUserData: vi.fn(), - storeUserData: vi.fn(), - dispatchCustomEvent: vi.fn() +vi.mock(import('@/scripts/api'), async () => { + const { fromPartial } = await import('@total-typescript/shoehorn') + return { + api: fromPartial({ + getUserData: vi.fn(), + storeUserData: vi.fn(), + dispatchCustomEvent: vi.fn() + }) } -})) - -vi.mock('@/platform/workflow/persistence/stores/workflowDraftStoreV2', () => ({ - useWorkflowDraftStoreV2: vi.fn(() => ({ - getDraft, - markDraftUsed: vi.fn(), - removeDraft: vi.fn() - })) -})) - -vi.mock('@/platform/settings/settingStore', () => ({ - useSettingStore: vi.fn(() => ({ - get: getSetting - })) -})) - -vi.mock('@/scripts/app', () => ({ - app: { - graph: {}, - rootGraph: { serialize: vi.fn(() => ({ nodes: [], links: [] })) }, - loadGraphData: vi.fn(() => Promise.resolve()), - canvas: { ds: { scale: 1, offset: [0, 0] } }, - ui: { autoQueueEnabled: false, autoQueueMode: 'instant' } +}) + +vi.mock(import('@/scripts/app'), async () => { + const { fromPartial } = await import('@total-typescript/shoehorn') + return { + app: fromPartial({ + graph: {}, + rootGraph: { serialize: vi.fn(() => ({ nodes: [], links: [] })) }, + loadGraphData: vi.fn(() => Promise.resolve()), + canvas: { ds: { scale: 1, offset: [0, 0] } }, + ui: { autoQueueEnabled: false, autoQueueMode: 'instant' } + }) } -})) - -// `ComfyWorkflow.load()` dynamically imports `changeTracker`, which in turn -// imports these stores. They are unused by the save/document-identity -// behavior under test here, but mirror changeTracker.test.ts's mocks so the -// dynamic import resolves without dragging in their real (DOM/app-bound) -// implementations. -vi.mock('@/stores/executionStore', () => ({ - useExecutionStore: vi.fn(() => ({})) -})) -vi.mock('@/stores/nodeOutputStore', () => ({ - useNodeOutputStore: vi.fn(() => ({ - snapshotOutputs: vi.fn(() => ({})), - restoreOutputs: vi.fn() - })) -})) -vi.mock('@/stores/subgraphNavigationStore', () => ({ - useSubgraphNavigationStore: vi.fn(() => ({ - exportState: vi.fn(() => []), - restoreState: vi.fn() - })) -})) +}) await import('@/scripts/changeTracker') @@ -90,7 +55,7 @@ async function createLoadedWorkflow(path = 'workflows/test.json') { return workflow } -describe('ComfyWorkflow document identity (ADR-0024)', () => { +describe('ComfyWorkflow document identity (ADR-GRAPH-DOCUMENT-0024)', () => { it('mints a clean local-only document id for persisted content', async () => { const workflow = await createLoadedWorkflow() expect(workflow.documentId).not.toBeNull() @@ -122,9 +87,11 @@ describe('ComfyWorkflow document identity (ADR-0024)', () => { it('marks a restored draft dirty against the persisted baseline', async () => { const draftState = { nodes: [], links: [], version: 1 } - getSetting.mockReturnValueOnce(true) - getDraft.mockReturnValueOnce({ + vi.mocked(useSettingStore().get).mockReturnValueOnce(true) + vi.mocked(useWorkflowDraftStoreV2().getDraft).mockReturnValueOnce({ data: JSON.stringify(draftState), + name: 'test', + isTemporary: false, updatedAt: 1 }) diff --git a/src/platform/workflow/management/stores/comfyWorkflow.ts b/src/platform/workflow/management/stores/comfyWorkflow.ts index 615f87737fe..f5dc5f67072 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.ts @@ -46,7 +46,7 @@ export class ComfyWorkflow extends UserFile { */ changeTracker: ChangeTracker | null = null /** - * This workflow's `GraphDocument` registry identity (ADR-0024). Created + * This workflow's `GraphDocument` registry identity (ADR-GRAPH-DOCUMENT-0024). Created * local-only (no `workflow_id`) the first time the workflow is loaded and * held for the instance's lifetime. Unload retains it, and later loads of * the same instance reuse it until an explicit document closer is wired. @@ -161,7 +161,7 @@ export class ComfyWorkflow extends UserFile { const initialState = JSON.parse(this.originalContent) const { ChangeTracker } = await import('@/scripts/changeTracker') this.changeTracker = markRaw(new ChangeTracker(this, initialState)) - // Local-only document identity (ADR-0024): every loaded workflow gets a + // Local-only document identity (ADR-GRAPH-DOCUMENT-0024): every loaded workflow gets a // registry entry, whether or not it is ever bound to a cloud // `workflow_id` (that mapping is layered on separately, e.g. by the // agent panel). Minted once per load; reused across re-entrant loads of diff --git a/src/scripts/changeTracker.ts b/src/scripts/changeTracker.ts index 602f633a93c..4d7fcfe4ca3 100644 --- a/src/scripts/changeTracker.ts +++ b/src/scripts/changeTracker.ts @@ -376,7 +376,7 @@ export class ChangeTracker { ) // Every call site of updateModified() already gated on a real state // change (activeState just moved to a new snapshot), so this maps 1:1 - // onto the registry's "mutated" event (ADR-0024 dirty tracking). + // onto the registry's "mutated" event (ADR-GRAPH-DOCUMENT-0024 dirty tracking). // Undo/redo call in too: moving activeState to a prior/later snapshot // is still a committed change to the document's current content. if (workflow.documentId) diff --git a/src/stores/graphDocumentStore.test.ts b/src/stores/graphDocumentStore.test.ts index afe807dc41e..62320f52138 100644 --- a/src/stores/graphDocumentStore.test.ts +++ b/src/stores/graphDocumentStore.test.ts @@ -1,6 +1,4 @@ -import { createTestingPinia } from '@pinia/testing' -import { setActivePinia } from 'pinia' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' @@ -12,10 +10,6 @@ const scope = { } describe('useGraphDocumentStore', () => { - beforeEach(() => { - setActivePinia(createTestingPinia({ stubActions: false })) - }) - it('creates local-only documents that are not agent-addressable', () => { const store = useGraphDocumentStore() const documentId = store.createDocument() diff --git a/src/stores/graphDocumentStore.ts b/src/stores/graphDocumentStore.ts index fc323be07df..5c7b6e1c127 100644 --- a/src/stores/graphDocumentStore.ts +++ b/src/stores/graphDocumentStore.ts @@ -41,7 +41,7 @@ export interface GraphHydrationTicket { } /** - * The GraphDocument registry (ADR-0024): every workflow document is a + * The GraphDocument registry (ADR-GRAPH-DOCUMENT-0024): every workflow document is a * first-class entry keyed by a stable frontend `document_id`, whether or not * a tab, renderer, or cloud `workflow_id` exists for it. The registry owns * the optional `workflow_id → document_id` mapping and rejects duplicate or diff --git a/src/types/documentId.ts b/src/types/documentId.ts index 11f84c2bbaf..81360e8b551 100644 --- a/src/types/documentId.ts +++ b/src/types/documentId.ts @@ -1,7 +1,7 @@ import { createUuidv4 } from '@/utils/uuid' /** - * Stable frontend-owned identity of a `GraphDocument` (ADR-0024). Every + * Stable frontend-owned identity of a `GraphDocument` (ADR-GRAPH-DOCUMENT-0024). Every * document has one, including local and unsaved workflows. A cloud-backed * document may additionally map a canonical `workflow_id` — the wire address * used by agent commands — but that mapping lives in the document registry; diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index d942a2f5393..06193ca4f53 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -179,7 +179,7 @@ const resolveDocumentId = (workflowId: string) => ) /** * Record every successful write against the target's document so its - * revision advances (ADR-0024 dirty tracking). Each method resolves the + * revision advances (ADR-GRAPH-DOCUMENT-0024 dirty tracking). Each method resolves the * document id when the write starts — not at wrapper creation (the workflow * may have been rebound to a new document since) and not at success time * (the write itself can synchronously trigger a rebind, and the mutation @@ -211,7 +211,7 @@ const withMutationTracking = ( const graphMutations = (workflowId: string) => { const existing = graphMutationsByWorkflow.get(workflowId) if (existing) return existing - // Document identity is early-bound (ADR-0024): the registry entry is + // Document identity is early-bound (ADR-GRAPH-DOCUMENT-0024): the registry entry is // created when the target is first addressed, not at commit time. Commit // scope resolution then records/refreshes the entry's scope, so a target // whose tab is momentarily unresolved still commits into its own document. diff --git a/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts b/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts index 7df7b0a48d7..187105a3c69 100644 --- a/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts +++ b/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts @@ -6,9 +6,7 @@ import { readStamps } from '@comfyorg/comfy-multi-player' import type { WidgetCatalog } from '@comfyorg/comfy-multi-player' -import { createTestingPinia } from '@pinia/testing' -import { setActivePinia } from 'pinia' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import * as Y from 'yjs' import { createActivationCoordinator } from '@/core/graph/document/activationCoordinator' @@ -121,11 +119,7 @@ function loadedCoordinator() { }) } -describe('document activation persistence (ADR-0024 seam)', () => { - beforeEach(() => { - setActivePinia(createTestingPinia({ stubActions: false })) - }) - +describe('document activation persistence (ADR-GRAPH-DOCUMENT-0024 seam)', () => { it('serializes byte-identically across Base/ECS/Nodes-2.0 activation cycles and save/reload', async () => { const scope = scopeFor('root') const mutations = mutationsFor(scope) diff --git a/src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts b/src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts index e04af252e0d..d495e0cc2df 100644 --- a/src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts +++ b/src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts @@ -1,6 +1,4 @@ -import { createTestingPinia } from '@pinia/testing' -import { setActivePinia } from 'pinia' -import { beforeEach, describe, expect, it } from 'vitest' +import { describe, expect, it } from 'vitest' import * as Y from 'yjs' import { createDetachedTargetSession } from '@/core/graph/document/detachedTargetSession' @@ -106,10 +104,6 @@ function ecsSnapshot() { } describe('detached target commit atomicity', () => { - beforeEach(() => { - setActivePinia(createTestingPinia({ stubActions: false })) - }) - it('publishes nothing when a later commit step fails, then retries once', () => { let refused: NodeId | null = toNodeId(8) const { port: layout, layouts } = layoutOwner(() => refused) diff --git a/src/workbench/extensions/agent/crdt/targetFrameProjection.ts b/src/workbench/extensions/agent/crdt/targetFrameProjection.ts index 75b1b87f22c..d84f487c831 100644 --- a/src/workbench/extensions/agent/crdt/targetFrameProjection.ts +++ b/src/workbench/extensions/agent/crdt/targetFrameProjection.ts @@ -26,7 +26,7 @@ function plain(value: unknown): unknown { * Staged-doc counterpart of the adapter's live readers: the adapter reads * incremental observer effects off its bound follower doc, while this reads * whole snapshots off a detached session's staged doc. Kept local because the - * projection must never depend on adapter internals (ADR-0024's seam). + * projection must never depend on adapter internals (ADR-GRAPH-DOCUMENT-0024's seam). */ function readSemanticNode(doc: Y.Doc, id: string): SemanticNodePayload | null { const source = nodesMap(doc).get(id) From bef50759d417099f0dc673a7ff048639f02119c9 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 12 Sep 2026 19:05:07 +0000 Subject: [PATCH 28/37] fix: contain graph lease disposal failures --- src/stores/graphDocumentStore.test.ts | 67 ++++++++++++++++++++++++--- src/stores/graphDocumentStore.ts | 15 ++++-- 2 files changed, 73 insertions(+), 9 deletions(-) diff --git a/src/stores/graphDocumentStore.test.ts b/src/stores/graphDocumentStore.test.ts index 62320f52138..79d84f2d377 100644 --- a/src/stores/graphDocumentStore.test.ts +++ b/src/stores/graphDocumentStore.test.ts @@ -187,7 +187,9 @@ describe('useGraphDocumentStore', () => { store.getDocument(documentId)?.state.revision ?? -1 const dispose = vi.fn() const lease = { graph: {}, dispose } - store.completeGraphHydration(store.beginGraphHydration(documentId)!, lease) + const hydration = store.beginGraphHydration(documentId) + if (hydration === null) throw new Error('beginGraphHydration failed') + store.completeGraphHydration(hydration, lease) store.markMutated(documentId) expect( store.closeDocument(documentId, { @@ -250,8 +252,11 @@ describe('useGraphDocumentStore', () => { const store = useGraphDocumentStore() const documentId = store.createDocument() if (documentId === null) throw new Error('createDocument failed') - const first = store.beginGraphHydration(documentId)! - const second = store.beginGraphHydration(documentId)! + const first = store.beginGraphHydration(documentId) + const second = store.beginGraphHydration(documentId) + if (first === null || second === null) { + throw new Error('beginGraphHydration failed') + } const staleDispose = vi.fn() const winningDispose = vi.fn() const stale = { graph: { id: 'stale' }, dispose: staleDispose } @@ -271,11 +276,15 @@ describe('useGraphDocumentStore', () => { store.hydrateDocument(documentId, scope) const firstDispose = vi.fn() const secondDispose = vi.fn() - store.completeGraphHydration(store.beginGraphHydration(documentId)!, { + const firstHydration = store.beginGraphHydration(documentId) + if (firstHydration === null) throw new Error('beginGraphHydration failed') + store.completeGraphHydration(firstHydration, { graph: { id: 'first' }, dispose: firstDispose }) - store.completeGraphHydration(store.beginGraphHydration(documentId)!, { + const secondHydration = store.beginGraphHydration(documentId) + if (secondHydration === null) throw new Error('beginGraphHydration failed') + store.completeGraphHydration(secondHydration, { graph: { id: 'second' }, dispose: secondDispose }) @@ -289,11 +298,57 @@ describe('useGraphDocumentStore', () => { expect(secondDispose).toHaveBeenCalledOnce() }) + it('publishes a replacement when disposing the previous lease throws', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument() + if (documentId === null) throw new Error('createDocument failed') + const firstHydration = store.beginGraphHydration(documentId) + if (firstHydration === null) throw new Error('beginGraphHydration failed') + store.completeGraphHydration(firstHydration, { + graph: { id: 'first' }, + dispose: () => { + throw new Error('dispose failed') + } + }) + const replacement = { graph: { id: 'replacement' }, dispose: vi.fn() } + const replacementHydration = store.beginGraphHydration(documentId) + if (replacementHydration === null) { + throw new Error('beginGraphHydration failed') + } + + expect( + store.completeGraphHydration(replacementHydration, replacement) + ).toBe(true) + expect(store.graphLeaseOf(documentId)).toBe(replacement) + }) + + it('closes a document when disposing its graph lease throws', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument() + if (documentId === null) throw new Error('createDocument failed') + store.hydrateDocument(documentId, scope) + const hydration = store.beginGraphHydration(documentId) + if (hydration === null) throw new Error('beginGraphHydration failed') + store.completeGraphHydration(hydration, { + graph: {}, + dispose: () => { + throw new Error('dispose failed') + } + }) + + expect( + store.closeDocument(documentId, { atRevision: 0, discardChanges: true }) + ).toBe(true) + expect(store.getDocument(documentId)?.state.phase).toBe('closed') + expect(store.graphLeaseOf(documentId)).toBeNull() + }) + it('disposes hydration that completes after close', () => { const store = useGraphDocumentStore() const documentId = store.createDocument() if (documentId === null) throw new Error('createDocument failed') - const ticket = store.beginGraphHydration(documentId)! + const ticket = store.beginGraphHydration(documentId) + if (ticket === null) throw new Error('beginGraphHydration failed') const dispose = vi.fn() expect( diff --git a/src/stores/graphDocumentStore.ts b/src/stores/graphDocumentStore.ts index 5c7b6e1c127..558deb5e9a6 100644 --- a/src/stores/graphDocumentStore.ts +++ b/src/stores/graphDocumentStore.ts @@ -10,6 +10,7 @@ import type { DocumentPersistenceState, DocumentTrackingState } from '@/core/graph/document/documentLifecycle' +import { reportError } from '@/platform/telemetry/reportError' import type { DocumentId } from '@/types/documentId' import { createDocumentId } from '@/types/documentId' import type { GraphScope } from '@/types/graphScopeId' @@ -81,6 +82,14 @@ export const useGraphDocumentStore = defineStore('graphDocument', () => { return graphLeases.get(documentId)?.lease ?? null } + function disposeLease(lease: DocumentGraphLease): void { + try { + lease.dispose() + } catch (error) { + reportError(error, { errorType: 'document_graph_lease_disposal_failure' }) + } + } + function beginGraphHydration( documentId: DocumentId ): GraphHydrationTicket | null { @@ -105,7 +114,7 @@ export const useGraphDocumentStore = defineStore('graphDocument', () => { entry.state.phase === 'closed' || hydrationGenerations.get(ticket.documentId) !== ticket.generation ) { - lease.dispose() + disposeLease(lease) return false } const previous = graphLeases.get(ticket.documentId) @@ -113,7 +122,7 @@ export const useGraphDocumentStore = defineStore('graphDocument', () => { generation: ticket.generation, lease }) - if (previous && previous.lease !== lease) previous.lease.dispose() + if (previous && previous.lease !== lease) disposeLease(previous.lease) return true } @@ -121,7 +130,7 @@ export const useGraphDocumentStore = defineStore('graphDocument', () => { const current = graphLeases.get(documentId) if (!current) return false graphLeases.delete(documentId) - current.lease.dispose() + disposeLease(current.lease) return true } From edfc1f20dba363898e4c7e424be237daa758b870 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 12 Sep 2026 19:46:54 +0000 Subject: [PATCH 29/37] test(graph): distinguish cross-target assertion modes Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16375#discussion_r3984033349 --- .../document/detachedTargetSession.test.ts | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/src/core/graph/document/detachedTargetSession.test.ts b/src/core/graph/document/detachedTargetSession.test.ts index 3d7d99a5ef8..d6c5bbdf0d1 100644 --- a/src/core/graph/document/detachedTargetSession.test.ts +++ b/src/core/graph/document/detachedTargetSession.test.ts @@ -58,6 +58,14 @@ function readNodes(update: Uint8Array): Record { const acceptAll: TargetFrameApplyPort = { apply: () => true } const rejectAll: TargetFrameApplyPort = { apply: () => false } +function captureError(action: () => unknown): unknown { + try { + action() + } catch (error) { + return error + } +} + describe('createDetachedTargetSession', () => { it('commits queued frames in order and reproduces the host state byte-exactly', () => { const source = createFrameSource() @@ -387,16 +395,43 @@ describe('createDetachedTargetSession', () => { expect(session.snapshot()).toEqual(beforeDestroy) }) - it('rejects frames addressed to another target loudly', () => { + it('rejects frames addressed to another target with a TypeError in production', () => { vi.stubEnv('DEV', false) const session = createDetachedTargetSession(WORKFLOW_ID) const stranger = createFrameSource('wf-other') - expect(() => + const thrown = captureError(() => session.enqueue( stranger.frame((doc) => setNode(doc, '1', { type: 'Source' })) ) - ).toThrow(/frames must never cross targets/) + ) + + expect(thrown).toBeInstanceOf(TypeError) + expect(thrown).toEqual( + expect.objectContaining({ + message: expect.stringMatching(/frames must never cross targets/) + }) + ) + }) + + it('rejects frames addressed to another target with an assertion error in development', () => { + vi.stubEnv('DEV', true) + const session = createDetachedTargetSession(WORKFLOW_ID) + const stranger = createFrameSource('wf-other') + + const thrown = captureError(() => + session.enqueue( + stranger.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + ) + + expect(thrown).toBeInstanceOf(Error) + expect(thrown).not.toBeInstanceOf(TypeError) + expect(thrown).toEqual( + expect.objectContaining({ + message: expect.stringMatching(/frames must never cross targets/) + }) + ) }) it('isCommitted answers for any sequence at or below the committed head of the same lineage', () => { From 5ade35e187a32cd77e83273534673506392d3d28 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 14 Sep 2026 06:49:51 +0000 Subject: [PATCH 30/37] fix(graph): preserve newer shared hydration lease --- src/stores/graphDocumentStore.test.ts | 19 +++++++++++++++++++ src/stores/graphDocumentStore.ts | 3 ++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/stores/graphDocumentStore.test.ts b/src/stores/graphDocumentStore.test.ts index 79d84f2d377..9f48e79ada6 100644 --- a/src/stores/graphDocumentStore.test.ts +++ b/src/stores/graphDocumentStore.test.ts @@ -269,6 +269,25 @@ describe('useGraphDocumentStore', () => { expect(winningDispose).not.toHaveBeenCalled() }) + it('does not dispose a shared lease published by a newer hydration', () => { + const store = useGraphDocumentStore() + const documentId = store.createDocument() + if (documentId === null) throw new Error('createDocument failed') + const older = store.beginGraphHydration(documentId) + const newer = store.beginGraphHydration(documentId) + if (older === null || newer === null) { + throw new Error('beginGraphHydration failed') + } + const dispose = vi.fn() + const sharedLease = { graph: { id: 'shared' }, dispose } + + expect(store.completeGraphHydration(newer, sharedLease)).toBe(true) + expect(store.completeGraphHydration(older, sharedLease)).toBe(false) + + expect(store.graphLeaseOf(documentId)).toBe(sharedLease) + expect(dispose).not.toHaveBeenCalled() + }) + it('disposes replaced and closed graph leases exactly once', () => { const store = useGraphDocumentStore() const documentId = store.createDocument() diff --git a/src/stores/graphDocumentStore.ts b/src/stores/graphDocumentStore.ts index 558deb5e9a6..50aee5324c7 100644 --- a/src/stores/graphDocumentStore.ts +++ b/src/stores/graphDocumentStore.ts @@ -114,7 +114,8 @@ export const useGraphDocumentStore = defineStore('graphDocument', () => { entry.state.phase === 'closed' || hydrationGenerations.get(ticket.documentId) !== ticket.generation ) { - disposeLease(lease) + const current = graphLeases.get(ticket.documentId) + if (current?.lease !== lease) disposeLease(lease) return false } const previous = graphLeases.get(ticket.documentId) From 8cdb944f7cf71fe57c1991a02fc993b9a632147d Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 14 Sep 2026 06:49:57 +0000 Subject: [PATCH 31/37] fix(graph): limit no-capture layout rollback --- src/core/graph/graphMutations.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/core/graph/graphMutations.ts b/src/core/graph/graphMutations.ts index 428be676d5f..1037f5961fe 100644 --- a/src/core/graph/graphMutations.ts +++ b/src/core/graph/graphMutations.ts @@ -961,7 +961,12 @@ export function createGraphMutations(deps: GraphMutationsDeps): GraphMutations { flushLayout(scope, layoutOps, context) } catch (error) { if (restoreLayout) restoreLayout.restore(context) - else deps.layout.deleteNodes(scope, touched, context) + else { + const created = layoutOps.flatMap((op) => + op.kind === 'create' ? [op.nodeId] : [] + ) + deps.layout.deleteNodes(scope, created, context) + } restoreSemantic(context) throw error } From bd7c172f7fcd8c9faa5a1ff3031d68e4ea64ba82 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 14 Sep 2026 06:49:57 +0000 Subject: [PATCH 32/37] test(graph): cover partial detached-session drain --- .../document/detachedTargetSession.test.ts | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/core/graph/document/detachedTargetSession.test.ts b/src/core/graph/document/detachedTargetSession.test.ts index d6c5bbdf0d1..8adb350b465 100644 --- a/src/core/graph/document/detachedTargetSession.test.ts +++ b/src/core/graph/document/detachedTargetSession.test.ts @@ -450,4 +450,26 @@ describe('createDetachedTargetSession', () => { expect(session.isCommitted(`other-lineage:1`)).toBe(false) expect(session.isCommitted('malformed')).toBe(false) }) + + it('drainAll reports commits completed before a failed head frame', () => { + const source = createFrameSource() + const session = createDetachedTargetSession(WORKFLOW_ID) + session.enqueue( + source.frame((doc) => setNode(doc, '1', { type: 'Source' })) + ) + session.enqueue(source.frame((doc) => setNode(doc, '1', { title: 'a' }))) + let calls = 0 + const failSecond: TargetFrameApplyPort = { + apply: () => ++calls === 1 + } + + expect(session.drainAll(failSecond)).toEqual({ + committed: 1, + stoppedBy: { status: 'failed', seq: 2 } + }) + expect(session.snapshot()).toMatchObject({ + committedSeq: 1, + queuedFrames: 1 + }) + }) }) From bf29f4439d919177fdc6c0bfca7dcef242dad663 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 14 Sep 2026 06:49:57 +0000 Subject: [PATCH 33/37] refactor(graph): narrow serializer projections --- src/core/graph/document/documentSerializer.ts | 38 ++++++++++++------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/src/core/graph/document/documentSerializer.ts b/src/core/graph/document/documentSerializer.ts index b8d0dc0a126..86974f67582 100644 --- a/src/core/graph/document/documentSerializer.ts +++ b/src/core/graph/document/documentSerializer.ts @@ -30,11 +30,11 @@ function canonicalize(value: unknown, depth = 0): unknown { if (value instanceof Map || value instanceof Set) return canonicalize([...value], depth + 1) if (typeof value === 'object' && value !== null) { - const source = value as Record const result: Record = {} - for (const key of Object.keys(source).sort()) { + for (const key of Object.keys(value).sort()) { if (RENDER_ONLY_KEYS.has(key)) continue - const entry = canonicalize(source[key], depth + 1) + const sourceValue: unknown = Reflect.get(value, key) + const entry = canonicalize(sourceValue, depth + 1) if (entry !== undefined) result[key] = entry } return result @@ -49,9 +49,7 @@ function canonicalize(value: unknown, depth = 0): unknown { * `hasErrors`, `boundingRect`, and the deprecated link-store-derived * `link`/`links` getters. */ -function pickSlot(slot: INodeInputSlot | INodeOutputSlot) { - const input = slot as Partial - const output = slot as Partial +function pickCommonSlot(slot: INodeInputSlot | INodeOutputSlot) { return { name: slot.name, localized_name: slot.localized_name, @@ -64,13 +62,25 @@ function pickSlot(slot: INodeInputSlot | INodeOutputSlot) { color_on: slot.color_on, locked: slot.locked, nameLocked: slot.nameLocked, - pos: slot.pos, - widget: input.widget - ? { name: input.widget.name, type: input.widget.type } + pos: slot.pos + } +} + +function pickInputSlot(slot: INodeInputSlot) { + return { + ...pickCommonSlot(slot), + widget: slot.widget + ? { name: slot.widget.name, type: slot.widget.type } : undefined, - widgetId: input.widgetId, - alwaysVisible: input.alwaysVisible, - slot_index: output.slot_index + widgetId: slot.widgetId, + alwaysVisible: slot.alwaysVisible + } +} + +function pickOutputSlot(slot: INodeOutputSlot) { + return { + ...pickCommonSlot(slot), + slot_index: slot.slot_index } } @@ -94,8 +104,8 @@ export function serializeDocumentScope(scope: GraphScope): Uint8Array { .sort((left, right) => compareNodeIds(left.id, right.id)) .map(({ graphId: _graphId, lastSerialization: _cache, ...semantic }) => ({ ...semantic, - inputs: semantic.inputs.map(pickSlot), - outputs: semantic.outputs.map(pickSlot), + inputs: semantic.inputs.map(pickInputSlot), + outputs: semantic.outputs.map(pickOutputSlot), widgets: widgetStore .getNodeWidgets(scope.rootGraphId, semantic.id) .map(({ name, type, value }) => ({ name, type, value })) From 158cbf29c6a2d971585a894223499023e21eb6d8 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 14 Sep 2026 06:49:57 +0000 Subject: [PATCH 34/37] test(graph): use typed serializer fixtures --- .../graph/document/documentSerializer.test.ts | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/core/graph/document/documentSerializer.test.ts b/src/core/graph/document/documentSerializer.test.ts index 042094e5000..86580ab2f69 100644 --- a/src/core/graph/document/documentSerializer.test.ts +++ b/src/core/graph/document/documentSerializer.test.ts @@ -14,7 +14,11 @@ import { toLinkId } from '@/types/linkId' import { toNodeId } from '@/types/nodeId' import type { NodeState } from '@/types/nodeState' import { widgetId } from '@/types/widgetId' -import { createNodeState } from '@/utils/__tests__/litegraphTestUtils' +import { + createMockNodeInputSlot, + createMockNodeOutputSlot, + createNodeState +} from '@/utils/__tests__/litegraphTestUtils' function scopeFor(graphId: string): GraphScope { return { @@ -24,11 +28,11 @@ function scopeFor(graphId: string): GraphScope { } function inputSlot(overrides: Partial = {}): INodeInputSlot { - return { name: 'in', type: 'INT', ...overrides } as INodeInputSlot + return createMockNodeInputSlot({ name: 'in', type: 'INT', ...overrides }) } function outputSlot(overrides: Partial = {}): INodeOutputSlot { - return { name: 'out', type: 'INT', ...overrides } as INodeOutputSlot + return createMockNodeOutputSlot({ name: 'out', type: 'INT', ...overrides }) } function decode(bytes: Uint8Array): { @@ -80,13 +84,14 @@ describe('serializeDocumentScope', () => { // shape that would explode JSON.stringify if slots were spread as-is. const cyclicWidget: Record = { name: 'w' } cyclicWidget.self = cyclicWidget + const malformedInput = inputSlot({ + link: toLinkId(5), + hasErrors: true, + boundingRect: [0, 0, 10, 10] + }) + Object.defineProperty(malformedInput, '_widget', { value: cyclicWidget }) const scope = populateScope('root-junk', { - input: inputSlot({ - link: toLinkId(5), - _widget: cyclicWidget as never, - hasErrors: true, - boundingRect: [0, 0, 10, 10] - }), + input: malformedInput, output: outputSlot({ links: [toLinkId(5)], _data: { transient: true }, @@ -160,13 +165,13 @@ describe('serializeDocumentScope', () => { it('throws on pathologically deep semantic state instead of hanging', () => { vi.stubEnv('DEV', false) const scope = scopeFor('root-deep') - let deep: unknown = 0 + let deep: NodeState['properties'][string] = 0 for (let i = 0; i < 40; i++) deep = [deep] useNodeDataStore().registerNode( scope, createNodeState({ id: toNodeId(1), - properties: { deep: deep as NodeState['properties'][string] } + properties: { deep } }) ) From 6c696dfe84cd10e8a6c2e414c03a1f9ead47dda5 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 14 Sep 2026 06:50:04 +0000 Subject: [PATCH 35/37] fix(workflow): rebaseline forced remote reloads --- .../management/stores/comfyWorkflow.test.ts | 84 +++++++++++++------ .../management/stores/comfyWorkflow.ts | 9 +- 2 files changed, 62 insertions(+), 31 deletions(-) diff --git a/src/platform/workflow/management/stores/comfyWorkflow.test.ts b/src/platform/workflow/management/stores/comfyWorkflow.test.ts index e66f0bc9f10..2894e4d14ed 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.test.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' +import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { api } from '@/scripts/api' import type { ComfyApi } from '@/scripts/api' @@ -36,23 +37,44 @@ vi.mock(import('@/scripts/app'), async () => { await import('@/scripts/changeTracker') function mockLoadResponse(content: string) { - vi.mocked(api.getUserData).mockResolvedValue({ - status: 200, - text: () => Promise.resolve(content) - } as never) + vi.mocked(api.getUserData).mockResolvedValue( + new Response(content, { status: 200 }) + ) } function mockSaveResponse() { - vi.mocked(api.storeUserData).mockResolvedValue({ - json: () => Promise.resolve('workflows/test.json') - } as never) + vi.mocked(api.storeUserData).mockResolvedValue( + new Response(JSON.stringify('workflows/test.json')) + ) } -async function createLoadedWorkflow(path = 'workflows/test.json') { +async function createLoadedWorkflow( + path = 'workflows/test.json' +): Promise { const workflow = new ComfyWorkflow({ path, modified: 0, size: 10 }) mockLoadResponse(JSON.stringify({ nodes: [], links: [] })) - await workflow.load() - return workflow + return workflow.load() +} + +function documentIdOf(workflow: LoadedComfyWorkflow) { + const documentId = workflow.documentId + if (documentId === null) throw new Error('workflow has no document id') + return documentId +} + +function deferred() { + let resolvePromise: ((value: T) => void) | null = null + const promise = new Promise((resolve) => { + resolvePromise = resolve + }) + return { + promise, + resolve(value: T) { + if (resolvePromise === null) + throw new Error('deferred is not initialized') + resolvePromise(value) + } + } } describe('ComfyWorkflow document identity (ADR-GRAPH-DOCUMENT-0024)', () => { @@ -61,10 +83,11 @@ describe('ComfyWorkflow document identity (ADR-GRAPH-DOCUMENT-0024)', () => { expect(workflow.documentId).not.toBeNull() const store = useGraphDocumentStore() - const entry = store.getDocument(workflow.documentId!) + const documentId = documentIdOf(workflow) + const entry = store.getDocument(documentId) expect(entry).not.toBeNull() expect(entry?.workflowId).toBeNull() - expect(store.persistenceStateOf(workflow.documentId!)).toBe('clean') + expect(store.persistenceStateOf(documentId)).toBe('clean') }) it('reuses the same document id across a re-entrant load', async () => { @@ -75,6 +98,19 @@ describe('ComfyWorkflow document identity (ADR-GRAPH-DOCUMENT-0024)', () => { expect(workflow.documentId).toBe(firstId) }) + it('rebaselines a dirty document after a forced remote reload', async () => { + const workflow = await createLoadedWorkflow() + const store = useGraphDocumentStore() + const documentId = documentIdOf(workflow) + expect(store.markMutated(documentId)).toBe(true) + expect(store.persistenceStateOf(documentId)).toBe('dirty') + + mockLoadResponse(JSON.stringify({ nodes: [], links: [], version: 2 })) + await workflow.load({ force: true }) + + expect(store.persistenceStateOf(documentId)).toBe('clean') + }) + it('keeps the same document id across unload (no closer exists yet)', async () => { const workflow = await createLoadedWorkflow() const firstId = workflow.documentId @@ -98,13 +134,13 @@ describe('ComfyWorkflow document identity (ADR-GRAPH-DOCUMENT-0024)', () => { const workflow = await createLoadedWorkflow() const store = useGraphDocumentStore() - expect(store.persistenceStateOf(workflow.documentId!)).toBe('dirty') + expect(store.persistenceStateOf(documentIdOf(workflow))).toBe('dirty') }) it('keeps the persisted document clean when saving its current revision', async () => { const workflow = await createLoadedWorkflow() const store = useGraphDocumentStore() - const documentId = workflow.documentId! + const documentId = documentIdOf(workflow) expect(store.persistenceStateOf(documentId)).toBe('clean') mockSaveResponse() @@ -116,7 +152,7 @@ describe('ComfyWorkflow document identity (ADR-GRAPH-DOCUMENT-0024)', () => { it('reports dirty for a mutation committed after the last save', async () => { const workflow = await createLoadedWorkflow() const store = useGraphDocumentStore() - const documentId = workflow.documentId! + const documentId = documentIdOf(workflow) mockSaveResponse() await workflow.save() @@ -130,7 +166,7 @@ describe('ComfyWorkflow document identity (ADR-GRAPH-DOCUMENT-0024)', () => { const workflow = await createLoadedWorkflow() useWorkflowStore().attachWorkflow(workflow) const store = useGraphDocumentStore() - const documentId = workflow.documentId! + const documentId = documentIdOf(workflow) // Establish a saved baseline first so a later revision divergence can // actually be observed as 'dirty' rather than 'unsaved'. @@ -140,16 +176,12 @@ describe('ComfyWorkflow document identity (ADR-GRAPH-DOCUMENT-0024)', () => { // storeUserData resolves only after a mutation commits against the // same document, simulating a concurrent edit racing the in-flight // save. - let resolveSave!: (value: { json: () => Promise }) => void - vi.mocked(api.storeUserData).mockReturnValue( - new Promise((resolve) => { - resolveSave = resolve - }) as never - ) + const save = deferred() + vi.mocked(api.storeUserData).mockReturnValue(save.promise) const savePromise = workflow.save() - const previousState = workflow.changeTracker!.activeState - workflow.changeTracker!.activeState = { + const previousState = workflow.changeTracker.activeState + workflow.changeTracker.activeState = { ...previousState, nodes: [ { @@ -166,8 +198,8 @@ describe('ComfyWorkflow document identity (ADR-GRAPH-DOCUMENT-0024)', () => { } ] } - workflow.changeTracker!.updateModified(previousState) - resolveSave({ json: () => Promise.resolve('workflows/test.json') }) + workflow.changeTracker.updateModified(previousState) + save.resolve(new Response(JSON.stringify('workflows/test.json'))) await savePromise expect(api.storeUserData).toHaveBeenCalledWith( diff --git a/src/platform/workflow/management/stores/comfyWorkflow.ts b/src/platform/workflow/management/stores/comfyWorkflow.ts index f5dc5f67072..2ac4f2bd749 100644 --- a/src/platform/workflow/management/stores/comfyWorkflow.ts +++ b/src/platform/workflow/management/stores/comfyWorkflow.ts @@ -169,11 +169,10 @@ export class ComfyWorkflow extends UserFile { const graphDocumentStore = useGraphDocumentStore() if (this.documentId === null) { this.documentId = graphDocumentStore.createDocument() - if (this.documentId !== null) { - const persistedBaseline = graphDocumentStore.beginSave(this.documentId) - if (persistedBaseline) - graphDocumentStore.completeSave(persistedBaseline) - } + } + if (this.documentId !== null) { + const persistedBaseline = graphDocumentStore.beginSave(this.documentId) + if (persistedBaseline) graphDocumentStore.completeSave(persistedBaseline) } if (draftState && draftContent) { this.changeTracker.activeState = draftState From df402b1597855a789293d4e75d4f9329f459f29c Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 14 Sep 2026 06:50:04 +0000 Subject: [PATCH 36/37] test(agent): strengthen persistence isolation coverage --- .../documentActivationPersistence.integration.test.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts b/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts index 187105a3c69..c7219186ee1 100644 --- a/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts +++ b/src/workbench/extensions/agent/crdt/documentActivationPersistence.integration.test.ts @@ -17,6 +17,7 @@ import { serializeDocumentScope } from '@/core/graph/document/documentSerializer import { createGraphMutations } from '@/core/graph/graphMutations' import type { GraphMutations } from '@/core/graph/graphMutations' import { useGraphDocumentStore } from '@/stores/graphDocumentStore' +import { useNodeDataStore } from '@/stores/nodeDataStore' import type { DocumentId } from '@/types/documentId' import type { GraphScope } from '@/types/graphScopeId' import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' @@ -155,10 +156,10 @@ describe('document activation persistence (ADR-GRAPH-DOCUMENT-0024 seam)', () => expect(registry.markMutated(documentId)).toBe(true) const ticket = registry.beginSave(documentId) - expect(ticket).not.toBeNull() + if (ticket === null) throw new Error('beginSave returned no ticket') const savedBytes = serializeDocumentScope(scope) expect(registry.markMutated(documentId)).toBe(true) - expect(registry.completeSave(ticket!)).toBe(true) + expect(registry.completeSave(ticket)).toBe(true) expect(registry.persistenceStateOf(documentId)).toBe('dirty') const reloadSession = createDetachedTargetSession('wf') @@ -268,6 +269,11 @@ describe('document activation persistence (ADR-GRAPH-DOCUMENT-0024 seam)', () => commitHostState(sessionB, 'wf-b', hostB, mutationsB) expect(serializeDocumentScope(scopeA)).toEqual(bytesA) + expect( + useNodeDataStore() + .getGraphNodesFor(scopeB.rootGraphId, scopeB.owningGraphId) + .map(({ id, type }) => ({ id, type })) + ).toEqual([{ id: '2', type: 'Sink' }]) expect(serializeDocumentScope(scopeB)).not.toEqual(bytesA) sessionA.destroy() From 610652409cf28413c49f0f04f888774d96917c4e Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 14 Sep 2026 06:50:04 +0000 Subject: [PATCH 37/37] test(agent): cover link presentation rollback --- .../targetFrameProjection.atomicity.test.ts | 45 +++++++++++++++++-- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts b/src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts index d495e0cc2df..b36834a907e 100644 --- a/src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts +++ b/src/workbench/extensions/agent/crdt/targetFrameProjection.atomicity.test.ts @@ -4,11 +4,13 @@ import * as Y from 'yjs' import { createDetachedTargetSession } from '@/core/graph/document/detachedTargetSession' import { createGraphMutations } from '@/core/graph/graphMutations' import type { SemanticLayoutMutationPort } from '@/core/graph/graphMutations' +import { useLinkPresentationStore } from '@/stores/linkPresentationStore' import { useLinkStore } from '@/stores/linkStore' import { useNodeDataStore } from '@/stores/nodeDataStore' import { useWidgetValueStore } from '@/stores/widgetValueStore' import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' import type { NodeId } from '@/types/nodeId' +import { toLinkId } from '@/types/linkId' import { toNodeId } from '@/types/nodeId' import { widgetId } from '@/types/widgetId' import { createTargetFrameApplyPort } from '@/workbench/extensions/agent/crdt/targetFrameProjection' @@ -65,8 +67,15 @@ function targetHost() { const doc = new Y.Doc() let delivered = Y.encodeStateVector(doc) let seq = 0 - return function edit(mutate: (nodes: Y.Map>) => void) { - doc.transact(() => mutate(doc.getMap>('nodes'))) + return function edit( + mutate: (nodes: Y.Map>, links: Y.Map) => void + ) { + doc.transact(() => + mutate( + doc.getMap>('nodes'), + doc.getMap('links') + ) + ) const update = Y.encodeStateAsUpdate(doc, delivered) delivered = Y.encodeStateVector(doc) seq += 1 @@ -87,6 +96,16 @@ function putNode( node.set('type', type) node.set('pos', [x, 20]) node.set('size', [200, 100]) + if (!node.has('inputs')) { + const inputs = new Y.Array() + inputs.push([{ name: 'in', type: 'IMAGE', link: null }]) + node.set('inputs', inputs) + } + if (!node.has('outputs')) { + const outputs = new Y.Array() + outputs.push([{ name: 'out', type: 'IMAGE', links: [] }]) + node.set('outputs', outputs) + } node.set('widgets_values', { seed }) } @@ -185,21 +204,39 @@ describe('detached target commit atomicity', () => { ) const edit = targetHost() - session.enqueue(edit((nodes) => putNode(nodes, '7', 'Type7', 42, 10))) + session.enqueue( + edit((nodes, links) => { + putNode(nodes, '7', 'Type7', 42, 10) + putNode(nodes, '8', 'Type8', 43, 30) + links.set('9', [9, '7', 0, '8', 0, 'IMAGE']) + }) + ) expect(session.commitNext(applyPort).status).toBe('committed') + useLinkPresentationStore().patch(scope, toLinkId(9), { + hidden: true, + label: 'Retained' + }) const committed = ecsSnapshot() + const committedPresentation = useLinkPresentationStore().getPresentation( + scope, + toLinkId(9) + ) const committedLayouts = JSON.stringify([...layouts.entries()]) refused = toNodeId(9) session.enqueue( - edit((nodes) => { + edit((nodes, links) => { putNode(nodes, '7', 'Type7Replaced', 99, 500) putNode(nodes, '9', 'Type9', 7, 700) + links.delete('9') }) ) expect(session.commitNext(applyPort).status).toBe('failed') expect(ecsSnapshot()).toEqual(committed) + expect( + useLinkPresentationStore().getPresentation(scope, toLinkId(9)) + ).toEqual(committedPresentation) expect(JSON.stringify([...layouts.entries()])).toEqual(committedLayouts) expect(session.snapshot()).toMatchObject({ revision: 1,