diff --git a/src/composables/useWorkspaceInset.test.ts b/src/composables/useWorkspaceInset.test.ts index 550126a2f4c..4ec41a40169 100644 --- a/src/composables/useWorkspaceInset.test.ts +++ b/src/composables/useWorkspaceInset.test.ts @@ -59,6 +59,21 @@ describe('useWorkspaceInsetRight', () => { width.value = 960 await nextTick() - expect(readInset()).toBe('420px') + // Teardown clears the var rather than freezing it at its last published + // value - a docked surface unmounted mid-close (its host's `v-if` beats + // its own `docked.value ? width : 0` branch to the flush) must not leave + // every portaled overlay permanently offset. + expect(readInset()).toBe('0px') + }) + + it('leaves the incoming publisher alone when the outgoing one disposes', () => { + const outgoing = effectScope() + outgoing.run(() => useWorkspaceInsetRight(() => 420)) + runInScope(() => 960) + + // A mode switch mounts the new docked host before unmounting the old one. + outgoing.stop() + + expect(readInset()).toBe('960px') }) }) diff --git a/src/composables/useWorkspaceInset.ts b/src/composables/useWorkspaceInset.ts index 718760fa553..c583d4a22d7 100644 --- a/src/composables/useWorkspaceInset.ts +++ b/src/composables/useWorkspaceInset.ts @@ -1,4 +1,4 @@ -import { watchEffect } from 'vue' +import { onScopeDispose, watchEffect } from 'vue' /** * Width consumed by docked surfaces on the right of the workspace. @@ -9,11 +9,27 @@ import { watchEffect } from 'vue' */ export const WORKSPACE_INSET_RIGHT = '--workspace-inset-right' +let activePublisher: symbol | null = null + export function useWorkspaceInsetRight(widthPx: () => number): void { + const publisher = Symbol('workspace-inset-right') watchEffect(() => { + activePublisher = publisher document.documentElement.style.setProperty( WORKSPACE_INSET_RIGHT, `${widthPx()}px` ) }) + // A docked surface's own `docked.value ? width : 0` branch never runs once + // its host is unmounted BEFORE that branch flips (e.g. a parent `v-if` + // unmounts the whole component in the same flush as closing it) - clear + // the var directly on teardown so it cannot survive its publisher. + // + // Mode switches mount the incoming publisher before the outgoing one + // disposes (GraphCanvas and LinearView both host the dock), so only the + // surface still owning the variable may clear it. + onScopeDispose(() => { + if (activePublisher !== publisher) return + document.documentElement.style.setProperty(WORKSPACE_INSET_RIGHT, '0px') + }) } diff --git a/src/renderer/core/layout/store/layoutStoreMintDelivery.test.ts b/src/renderer/core/layout/store/layoutStoreMintDelivery.test.ts index fc5eacb7e0e..66100a1328a 100644 --- a/src/renderer/core/layout/store/layoutStoreMintDelivery.test.ts +++ b/src/renderer/core/layout/store/layoutStoreMintDelivery.test.ts @@ -156,6 +156,7 @@ describe('mint ports against the real layout store delivery', () => { const linkStore = useLinkStore() const severed = linkTopology(41, '2') linkStore.registerLink(scope, severed) + await realDelivery() minted.length = 0 const consoleError = vi .spyOn(console, 'error') diff --git a/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts b/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts index 8e6439be5ee..cb1bb60f1e0 100644 --- a/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts +++ b/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts @@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { defineComponent, nextTick, ref } from 'vue' import { i18n } from '@/i18n' +import { WORKSPACE_INSET_RIGHT } from '@/composables/useWorkspaceInset' import { reportError } from '@/platform/telemetry/reportError' import type { TurnId } from '@/workbench/extensions/agent/schemas/agentApiSchema' import { useAgentConversationStore } from '@/workbench/extensions/agent/stores/agent/agentConversationStore' @@ -65,6 +66,7 @@ function renderPanel() { describe('DockedAgentPanel', () => { beforeEach(() => { localStorage.clear() + document.documentElement.style.removeProperty(WORKSPACE_INSET_RIGHT) fetchApi.mockReset() fetchApi.mockResolvedValue(jsonResponse(404, { error: 'not found' })) vi.mocked(reportError).mockClear() @@ -84,6 +86,9 @@ describe('DockedAgentPanel', () => { timeout: 5000 }) ).toBeTruthy() + expect( + document.documentElement.style.getPropertyValue(WORKSPACE_INSET_RIGHT) + ).toBe(`${store.width}px`) }) it('restores the server run mode when the panel initializes', async () => { diff --git a/src/workbench/extensions/agent/components/agent/DockedAgentPanel.vue b/src/workbench/extensions/agent/components/agent/DockedAgentPanel.vue index 1596b735c72..8dde0670377 100644 --- a/src/workbench/extensions/agent/components/agent/DockedAgentPanel.vue +++ b/src/workbench/extensions/agent/components/agent/DockedAgentPanel.vue @@ -34,6 +34,7 @@ import { computed, defineAsyncComponent, defineComponent, h, ref } from 'vue' import { useI18n } from 'vue-i18n' import { reportError } from '@/platform/telemetry/reportError' +import { useWorkspaceInsetRight } from '@/composables/useWorkspaceInset' import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' import { useAgentRunModeStore } from '@/workbench/extensions/agent/stores/agent/agentRunModeStore' @@ -68,6 +69,7 @@ const agentPanelStore = useAgentPanelStore() const agentRunModeStore = useAgentRunModeStore() const { isOpen, enabled, width } = storeToRefs(agentPanelStore) const docked = computed(() => enabled.value && isOpen.value) +useWorkspaceInsetRight(() => (docked.value ? width.value : 0)) void agentRunModeStore.load().catch((error: unknown) => { reportError(error, { errorType: 'agent_run_mode_load_failure' }) diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts index 29b6c39c425..f32de063063 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts @@ -1,5 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { toLinkId } from '@/types/linkId' + import type { GraphOperation } from './graphOperations' import { attachLinkMintPort } from './linkMintPort' import type { @@ -10,6 +12,9 @@ import type { import { createMintSession } from './mintSession' import type { MintSession } from './mintSession' +const { reportError } = vi.hoisted(() => ({ reportError: vi.fn() })) +vi.mock(import('@/platform/telemetry/reportError'), () => ({ reportError })) + const ROOT_SCOPE: LinkScopeView = { rootGraphId: 'root-uuid', owningGraphId: 'root-uuid' @@ -21,7 +26,7 @@ const SUBGRAPH_SCOPE: LinkScopeView = { function topology(id: number): LinkTopologyView { return { - id, + id: toLinkId(id), originNodeId: 1, originSlot: 0, targetNodeId: 2, @@ -82,8 +87,9 @@ describe('attachLinkMintPort', () => { }) }) - it('mints a concrete connect for a local link placement', () => { + it('mints a concrete connect for a local link placement', async () => { place(ROOT_SCOPE, topology(41)) + await Promise.resolve() expect(minted).toEqual([ { @@ -121,14 +127,10 @@ describe('attachLinkMintPort', () => { }) it('surfaces a subgraph-interior placement observably instead of minting', () => { - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) place(SUBGRAPH_SCOPE, topology(41)) expect(minted).toEqual([]) - expect(consoleError).toHaveBeenCalledOnce() - consoleError.mockRestore() + expect(reportError).toHaveBeenCalledOnce() }) it('captures a severed link under both endpoints, consumed exactly once', () => { @@ -139,40 +141,34 @@ describe('attachLinkMintPort', () => { }) it('surfaces an unconsumed local disconnect as divergence after the sweep', async () => { - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) remove(ROOT_SCOPE, topology(41)) await afterSweep() - expect(consoleError).toHaveBeenCalledOnce() - expect(consoleError.mock.calls[0][1]).toBe(41) - consoleError.mockRestore() + expect(reportError).toHaveBeenCalledOnce() + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'agent_crdt_unrepresentable_link_change', + tags: expect.objectContaining({ linkId: 41 }) + }) + ) }) it('stays silent for a consumed severance (the delete carried it)', async () => { - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) remove(ROOT_SCOPE, topology(41)) port.severances.take('1') await afterSweep() - expect(consoleError).not.toHaveBeenCalled() - consoleError.mockRestore() + expect(reportError).not.toHaveBeenCalled() }) it('stays silent for teardown severances', async () => { - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) session.beginGraphTeardown() remove(ROOT_SCOPE, topology(41)) session.endGraphTeardown() await afterSweep() - expect(consoleError).not.toHaveBeenCalled() - consoleError.mockRestore() + expect(reportError).not.toHaveBeenCalled() }) it('sweeps the capture window: a later take finds nothing', async () => { @@ -191,4 +187,38 @@ describe('attachLinkMintPort', () => { expect(minted).toEqual([]) }) + + it('cancels a same-task deletion of an unflushed placement without a phantom connect', async () => { + place(ROOT_SCOPE, topology(41)) + remove(ROOT_SCOPE, topology(41)) + await afterSweep() + + // The canceled placement never reaches enqueue and is never reported as + // a `link connect` divergence (it did not ship). The severance sweep + // still runs and correctly reports the unconsumed disconnect - it was a + // real local delete that nothing (e.g. a delete_node mint) consumed. + expect(minted).toEqual([]) + expect(reportError).toHaveBeenCalledOnce() + expect(reportError).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining('link disconnect') + }), + expect.anything() + ) + }) + + it('flushes and surfaces pending placements on detach instead of discarding them silently', () => { + place(ROOT_SCOPE, topology(41)) + port.detach() + + expect(minted).toEqual([]) + expect(reportError).toHaveBeenCalledOnce() + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'agent_crdt_unrepresentable_link_change', + tags: expect.objectContaining({ linkId: 41 }) + }) + ) + }) }) diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.ts b/src/workbench/extensions/agent/crdt/linkMintPort.ts index 613fd5ce269..725da7e4188 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.ts @@ -2,13 +2,19 @@ * The blessed connect port: litegraph's registerLinkTopology bridge calls * linkStore synchronously for EVERY link change, so nothing escapes this seam. * Register/replace mint a CONCRETE connect (a replace displaces the incumbent - * register by LWW - no severance). Deletes cannot mint (no disconnect op in - * the frozen vocabulary): they feed the severance log for delete_node, and an - * unconsumed local severance surfaces as observable divergence after a double - * microtask (strictly after the layout store's single-microtask delivery). + * register by LWW - no severance). A placement is held for one microtask so + * a same-task delete can cancel it before it ships; cross-port ORDER is not + * this port's concern - the wiring's shared mint queue decides it. Deletes + * cannot mint (no disconnect op in the frozen vocabulary): they feed the + * severance log for delete_node, and an unconsumed local severance surfaces + * as observable divergence after a double microtask (strictly after the + * layout store's single-microtask delivery). */ import type { NodeId as WireNodeId } from '@comfyorg/comfy-multi-player' +import { reportError } from '@/platform/telemetry/reportError' +import type { LinkId } from '@/types/linkId' + import type { GraphOperation } from './graphOperations' import { shouldMint } from './mintGate' import type { MintSession } from './mintSession' @@ -25,7 +31,7 @@ export interface LinkScopeView { * link - the wiring feed filters those out before this port sees them. */ export interface LinkTopologyView { - id: string | number + id: LinkId originNodeId: string | number originSlot: number targetNodeId: string | number @@ -63,7 +69,7 @@ export interface LinkMintPortDeps { isEnabled(): boolean /** A semantic doc is bound for the active workflow. */ isDocBound(): boolean - /** Receives minted semantic operations (the sender's inbox). */ + /** Receives minted semantic operations (the wiring's shared mint queue). */ enqueue(operations: GraphOperation[]): void } @@ -73,7 +79,7 @@ export interface LinkMintPort { } interface SeveranceEntry { - linkId: WireNodeId + linkId: LinkId /** The gate was open at severance: unconsumed means a real divergence. */ mintable: boolean } @@ -82,10 +88,23 @@ function isRootScope(scope: LinkScopeView): boolean { return scope.owningGraphId === scope.rootGraphId } +/** Link ids are per root graph; two open workflows may both own link 41. */ +function placementKey( + scope: LinkScopeView, + topology: LinkTopologyView +): string { + return `${scope.rootGraphId}:${topology.id}` +} + export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { const severancesByNode = new Map() const consumedLinkIds = new Set() + const pendingPlacements = new Map< + string, + { operation: GraphOperation; linkId: LinkId } + >() let sweepScheduled = false + let detached = false function gateOpen(): boolean { return shouldMint({ @@ -95,12 +114,17 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { }) } - function surfaceUnrepresentable(what: string, id: string | number): void { + function surfaceUnrepresentable(what: string, id: LinkId): void { // A doc that no longer matches the local graph must be observable, // never silent (the surfacing-honesty principle). - console.error( - `[agent-crdt] ${what} has no wire op; the bound doc diverges from the local graph`, - id + reportError( + new Error( + `[agent-crdt] ${what} has no wire op; the bound doc diverges from the local graph` + ), + { + errorType: 'agent_crdt_unrepresentable_link_change', + tags: { change: what, linkId: id } + } ) } @@ -110,8 +134,10 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { surfaceUnrepresentable('subgraph-interior connect', topology.id) return } - deps.enqueue([ - { + const key = placementKey(scope, topology) + pendingPlacements.set(key, { + linkId: topology.id, + operation: { op: 'connect', link_id: topology.id, from_node: topology.originNodeId, @@ -120,7 +146,29 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { to_slot: topology.targetSlot, link_type: String(topology.type) } - ]) + }) + queueMicrotask(() => flushPlacement(key)) + } + + function flushPlacement(key: string): void { + const pending = pendingPlacements.get(key) + if (!pending) return + pendingPlacements.delete(key) + if (detached || !gateOpen()) { + surfaceUnrepresentable('link connect', pending.linkId) + return + } + deps.enqueue([pending.operation]) + } + + /** + * A same-task deletion that cancels an unflushed placement: no connect + * ever reached `deps.enqueue()`, so nothing diverges from the local graph + * (which also omits the link) - drop it silently rather than reporting a + * `link connect` divergence for an op that never shipped. + */ + function cancelPlacement(key: string): void { + pendingPlacements.delete(key) } function scheduleSweep(): void { @@ -156,6 +204,10 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { } function onDeleted(scope: LinkScopeView, topology: LinkTopologyView): void { + // A same-task placement that never flushed is canceled, not a real + // divergence: the local graph and the doc both end up without the link. + // Preserve mutation order for everything else that already flushed. + cancelPlacement(placementKey(scope, topology)) const entry: SeveranceEntry = { linkId: topology.id, mintable: gateOpen() && isRootScope(scope) @@ -182,6 +234,8 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { } }, detach() { + detached = true + for (const key of pendingPlacements.keys()) flushPlacement(key) detachPlaced() detachDeleted() } diff --git a/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts b/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts index 8610be8d1c2..3b3ad889efc 100644 --- a/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts +++ b/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts @@ -46,12 +46,24 @@ function topology(id: number, targetSlot = 3): LinkTopology { } } +/** Past the ports' double-microtask sweep and the shared queue's drain. */ async function afterSweep(): Promise { await Promise.resolve() await Promise.resolve() await Promise.resolve() } +function createNodeChange(id: number): LayoutChangeView { + return { + operation: { + type: 'createNode', + actor: 'user-abc', + nodeId: toNodeId(id), + layout: { position: { x: 10 * id, y: 20 * id } } + } + } +} + describe('attachMintPortWiring', () => { let minted: GraphOperation[] let wiring: MintPortWiring @@ -95,7 +107,7 @@ describe('attachMintPortWiring', () => { afterEach(() => wiring.detach()) - it('mints a root clear through the production intentional-clear entry point', () => { + it('mints a root clear through the production intentional-clear entry point', async () => { graphNodes.set('1', { id: toNodeId(1) }) graphNodes.set('2', { id: toNodeId(2) }) @@ -104,14 +116,16 @@ describe('attachMintPortWiring', () => { operation: { type: 'clearGraph', actor: 'user-abc' } }) }) + await afterSweep() expect(minted).toEqual([ { op: 'clear', removed_nodes: [toNodeId(1), toNodeId(2)] } ]) }) - it('mints a concrete connect when the real link store places a link', () => { + it('mints a concrete connect when the real link store places a link', async () => { useLinkStore().registerLink(ROOT_SCOPE, topology(41)) + await afterSweep() expect(minted).toEqual([ { @@ -152,6 +166,7 @@ describe('attachMintPortWiring', () => { const linkStore = useLinkStore() const severed = topology(41) linkStore.registerLink(ROOT_SCOPE, severed) + await afterSweep() minted.length = 0 linkStore.deleteLink(ROOT_SCOPE, severed) @@ -165,14 +180,94 @@ describe('attachMintPortWiring', () => { ]) }) - it('mints a name-keyed set_widget with the pre-write value from the real store', () => { + it('orders a same-task createNode before its connect when the store delivers a microtask late', async () => { + graphNodes.set('1', { serialize: () => ({ id: 1, type: 'LoadImage' }) }) + graphNodes.set('2', { + serialize: () => ({ id: 2, type: 'PreviewImage' }) + }) + + // The real store queues its whole batch on ONE microtask, so the sync + // link feed mints first; the shared queue still ships add_node first. + queueMicrotask(() => { + deliverLayoutChange(createNodeChange(1)) + deliverLayoutChange(createNodeChange(2)) + }) + useLinkStore().registerLink(ROOT_SCOPE, topology(41)) + await afterSweep() + + expect(minted.map((operation) => operation.op)).toEqual([ + 'add_node', + 'add_node', + 'connect' + ]) + }) + + it('orders a same-task createNode before its widget write, whichever port mints first', async () => { + graphNodes.set('7', { serialize: () => ({ id: 7, type: 'KSampler' }) }) + const widgetStore = useWidgetValueStore() + const id = widgetId(ROOT_ID, toNodeId(7), 'seed') + widgetStore.registerWidget(id, { type: 'number', value: 3 } as Parameters< + typeof widgetStore.registerWidget + >[1]) + + widgetStore.setValue(id, 42) + deliverLayoutChange(createNodeChange(7)) + await afterSweep() + + expect(minted.map((operation) => operation.op)).toEqual([ + 'add_node', + 'set_widget' + ]) + expect(minted).toHaveLength(2) + }) + + it('drops a widget write on a node the same task deletes', async () => { + const widgetStore = useWidgetValueStore() + const id = widgetId(ROOT_ID, toNodeId(7), 'seed') + widgetStore.registerWidget(id, { type: 'number', value: 3 } as Parameters< + typeof widgetStore.registerWidget + >[1]) + + widgetStore.setValue(id, 42) + deliverLayoutChange({ + operation: { type: 'deleteNode', actor: 'user-abc', nodeId: toNodeId(7) } + }) + await afterSweep() + + expect(minted).toEqual([ + { op: 'delete_node', node_id: '7', removed_links: [] } + ]) + }) + + it('a widget write in a LATER task than the delete is not pruned (drains are per task)', async () => { const widgetStore = useWidgetValueStore() const id = widgetId(ROOT_ID, toNodeId(7), 'seed') widgetStore.registerWidget(id, { type: 'number', value: 3 } as Parameters< typeof widgetStore.registerWidget >[1]) + deliverLayoutChange({ + operation: { type: 'deleteNode', actor: 'user-abc', nodeId: toNodeId(7) } + }) + await afterSweep() widgetStore.setValue(id, 42) + await afterSweep() + + expect(minted.map((operation) => operation.op)).toEqual([ + 'delete_node', + 'set_widget' + ]) + }) + + it('mints a name-keyed set_widget with the pre-write value from the real store', async () => { + const widgetStore = useWidgetValueStore() + const id = widgetId(ROOT_ID, toNodeId(7), 'seed') + widgetStore.registerWidget(id, { type: 'number', value: 3 } as Parameters< + typeof widgetStore.registerWidget + >[1]) + + widgetStore.setValue(id, 42) + await afterSweep() expect(minted).toEqual([ { @@ -185,7 +280,7 @@ describe('attachMintPortWiring', () => { ]) }) - it('mints a widget value written through a real widget', () => { + it('mints a widget value written through a real widget', async () => { const liveGraph = new LGraph() liveGraph.id = ROOT_ID const node = new LGraphNode('Test') @@ -195,6 +290,7 @@ describe('attachMintPortWiring', () => { graphNodes.set('7', node) widget.value = 42 + await afterSweep() expect(minted).toEqual([ { @@ -207,7 +303,7 @@ describe('attachMintPortWiring', () => { ]) }) - it('mints once when a store write is mirrored through the widget shim', () => { + it('mints once when a store write is mirrored through the widget shim', async () => { const liveGraph = new LGraph() liveGraph.id = ROOT_ID const node = new LGraphNode('Test') @@ -219,6 +315,7 @@ describe('attachMintPortWiring', () => { useWidgetValueStore().setValue(id, 42) widget.value = 42 + await afterSweep() expect(minted).toEqual([ { @@ -231,13 +328,14 @@ describe('attachMintPortWiring', () => { ]) }) - it('mints nothing for a setValue that did not apply', () => { + it('mints nothing for a setValue that did not apply', async () => { useWidgetValueStore().setValue(widgetId(ROOT_ID, toNodeId(9), 'missing'), 1) + await afterSweep() expect(minted).toEqual([]) }) - it('suppresses remote store calls from their call-carried context', () => { + it('suppresses remote store calls from their call-carried context', async () => { const context: RemoteMutationContext = { source: 'agent-remote', actor: 'agent:test', @@ -250,13 +348,14 @@ describe('attachMintPortWiring', () => { typeof widgetStore.registerWidget >[1]) const widget = widgetStore.setValue(id, 42, context) + await afterSweep() expect(link).toBeDefined() expect(widget).toBe(true) expect(minted).toEqual([]) }) - it('suppresses mints between the load-bracket hooks, fail-closed on a failed load', () => { + it('suppresses mints between the load-bracket hooks, fail-closed on a failed load', async () => { wiring.onBeforeGraphLoad() useLinkStore().registerLink(ROOT_SCOPE, topology(41)) expect(minted).toEqual([]) @@ -269,10 +368,11 @@ describe('attachMintPortWiring', () => { wiring.onAfterGraphConfigure() useLinkStore().registerLink(ROOT_SCOPE, topology(43, 4)) + await afterSweep() expect(minted).toHaveLength(1) }) - it('serializes add_node snapshots name-keyed, dropping non-value widgets', () => { + it('serializes add_node snapshots name-keyed, dropping non-value widgets', async () => { graphNodes.set('5', { serialize: () => ({ id: 5, @@ -294,6 +394,7 @@ describe('attachMintPortWiring', () => { layout: { position: { x: 10, y: 20 } } } }) + await afterSweep() expect(minted).toEqual([ { @@ -310,7 +411,7 @@ describe('attachMintPortWiring', () => { ]) }) - it('positive control: an unbound workflow runs normally, zero mint and zero blockage', () => { + it('positive control: an unbound workflow runs normally, zero mint and zero blockage', async () => { bound = false const widgetStore = useWidgetValueStore() const id = widgetId(ROOT_ID, toNodeId(7), 'seed') @@ -320,6 +421,7 @@ describe('attachMintPortWiring', () => { const placed = useLinkStore().registerLink(ROOT_SCOPE, topology(41)) const applied = widgetStore.setValue(id, 42) + await afterSweep() expect(minted).toEqual([]) expect(placed).toBeDefined() @@ -327,7 +429,7 @@ describe('attachMintPortWiring', () => { expect(widgetStore.getWidget(id)?.value).toBe(42) }) - it('stops observing both stores after detach', () => { + it('stops observing both stores after detach', async () => { wiring.detach() useLinkStore().registerLink(ROOT_SCOPE, topology(41)) const widgetStore = useWidgetValueStore() @@ -336,7 +438,18 @@ describe('attachMintPortWiring', () => { typeof widgetStore.registerWidget >[1]) widgetStore.setValue(id, 42) + await afterSweep() expect(minted).toEqual([]) }) + + it('detach flushes a queued mint instead of dropping it', () => { + graphNodes.set('5', { serialize: () => ({ id: 5, type: 'LoadImage' }) }) + deliverLayoutChange(createNodeChange(5)) + expect(minted).toEqual([]) + + wiring.detach() + + expect(minted.map((operation) => operation.op)).toEqual(['add_node']) + }) }) diff --git a/src/workbench/extensions/agent/crdt/mintPortWiring.ts b/src/workbench/extensions/agent/crdt/mintPortWiring.ts index 87233ad5799..54fc54e6d2f 100644 --- a/src/workbench/extensions/agent/crdt/mintPortWiring.ts +++ b/src/workbench/extensions/agent/crdt/mintPortWiring.ts @@ -5,6 +5,10 @@ * displaces incumbents internally). Load brackets are a fail-closed boolean * over beforeLoadGraph/afterConfigureGraph: a failed load leaves mints * suppressed until the next load's pair recloses. + * + * All three ports mint into ONE {@link MintQueue}, which is the only thing + * that talks to `deps.enqueue`: cross-port order is decided by its drain, not + * by which port's microtask happened to be inserted first. */ import type { LGraph } from '@/lib/litegraph/src/LGraph' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' @@ -23,6 +27,8 @@ import { attachLayoutMintPort } from './layoutMintPort' import type { LayoutChangeView, LayoutMintPort } from './layoutMintPort' import { attachLinkMintPort } from './linkMintPort' import { attachWidgetMintPort } from './widgetMintPort' +import { createMintQueue } from './mintQueue' +import type { MintQueue } from './mintQueue' import { createMintSession } from './mintSession' import type { MintSession } from './mintSession' @@ -39,7 +45,7 @@ export interface MintPortWiringDeps { isEnabled(): boolean /** A semantic doc is bound for the active workflow. */ isDocBound(): boolean - /** Receives minted semantic operations (the sender's inbox). */ + /** Receives each drained batch of minted operations (the sender's inbox). */ enqueue(operations: GraphOperation[]): void /** The layout store's `onChange`, injected by the composition root. */ layoutChanges(listener: (change: LayoutChangeView) => void): () => void @@ -126,6 +132,7 @@ function serializeForMint(node: LGraphNode): WorkflowNode | null { export function attachMintPortWiring(deps: MintPortWiringDeps): MintPortWiring { const session = createMintSession() + const queue: MintQueue = createMintQueue(deps.enqueue) type PlacedListener = Parameters< Parameters[0]['events']['onPlaced'] @@ -154,7 +161,7 @@ export function attachMintPortWiring(deps: MintPortWiringDeps): MintPortWiring { session, isEnabled: deps.isEnabled, isDocBound: deps.isDocBound, - enqueue: deps.enqueue + enqueue: queue.enqueue }) const layoutPort: LayoutMintPort = attachLayoutMintPort({ @@ -173,7 +180,7 @@ export function attachMintPortWiring(deps: MintPortWiringDeps): MintPortWiring { return (deps.getGraph()?._nodes ?? []).map((node) => node.id) } }, - enqueue: deps.enqueue + enqueue: queue.enqueue }) const widgetPort = attachWidgetMintPort({ @@ -196,7 +203,7 @@ export function attachMintPortWiring(deps: MintPortWiringDeps): MintPortWiring { if (!graph) return null return findSubgraphNodePathById(graph as unknown as LGraph, owningGraphId) }, - enqueue: deps.enqueue + enqueue: queue.enqueue }) const linkStore = useLinkStore() @@ -263,6 +270,7 @@ export function attachMintPortWiring(deps: MintPortWiringDeps): MintPortWiring { widgetPort.detach() layoutPort.detach() linkPort.detach() + queue.flush() } } activeWirings.add(wiring) diff --git a/src/workbench/extensions/agent/crdt/mintQueue.test.ts b/src/workbench/extensions/agent/crdt/mintQueue.test.ts new file mode 100644 index 00000000000..c6ce0574eb4 --- /dev/null +++ b/src/workbench/extensions/agent/crdt/mintQueue.test.ts @@ -0,0 +1,182 @@ +import { describe, expect, it } from 'vitest' + +import type { GraphOperation } from './graphOperations' +import { createMintQueue, orderMintedOperations } from './mintQueue' + +function addNode(id: number): GraphOperation { + return { + op: 'add_node', + node_id: id, + class_type: 'TestNode', + pos: [0, 0], + node: { id, type: 'TestNode' } + } +} + +function deleteNode(id: number): GraphOperation { + return { op: 'delete_node', node_id: id, removed_links: [] } +} + +function connect(linkId: number, from: number, to: number): GraphOperation { + return { + op: 'connect', + link_id: linkId, + from_node: from, + from_slot: 0, + to_node: to, + to_slot: 0, + link_type: 'IMAGE' + } +} + +function setWidget(nodeId: number, value: unknown): GraphOperation { + return { op: 'set_widget', node_id: nodeId, widget: 'seed', value, old: 0 } +} + +async function afterDrain(): Promise { + await Promise.resolve() + await Promise.resolve() +} + +describe('orderMintedOperations', () => { + it('lands structural ops before the connects and widget writes that need them', () => { + // The sync feeds mint first in a same-task createNode + registerLink + + // setValue; the layout store's add_node arrives a microtask later. + expect( + orderMintedOperations([ + connect(41, 1, 2), + setWidget(2, 'x'), + addNode(1), + addNode(2) + ]) + ).toEqual([addNode(1), addNode(2), connect(41, 1, 2), setWidget(2, 'x')]) + }) + + it('keeps layout-store order within the structural class', () => { + expect( + orderMintedOperations([deleteNode(1), addNode(1), addNode(2)]) + ).toEqual([deleteNode(1), addNode(1), addNode(2)]) + }) + + it('keeps mint order within the dependent class', () => { + expect( + orderMintedOperations([ + setWidget(2, 'a'), + connect(41, 1, 2), + setWidget(2, 'b') + ]) + ).toEqual([setWidget(2, 'a'), connect(41, 1, 2), setWidget(2, 'b')]) + }) + + it('drops a widget write or connect orphaned by a same-drain delete', () => { + expect( + orderMintedOperations([ + setWidget(2, 'x'), + setWidget(3, 'kept'), + connect(41, 1, 2), + connect(42, 1, 3), + deleteNode(2) + ]) + ).toEqual([deleteNode(2), setWidget(3, 'kept'), connect(42, 1, 3)]) + }) + + it('drops dependents when a node is added and then deleted', () => { + expect( + orderMintedOperations([ + addNode(2), + deleteNode(2), + setWidget(2, 'x'), + connect(41, 1, 2) + ]) + ).toEqual([addNode(2), deleteNode(2)]) + }) + + it("drops writes to a clear's removed nodes but not to nodes added after it", () => { + expect( + orderMintedOperations([ + setWidget(5, 'pre-clear'), + { op: 'clear', removed_nodes: [5, 6] }, + addNode(7), + setWidget(7, 'post-clear'), + connect(41, 6, 7) + ]) + ).toEqual([ + { op: 'clear', removed_nodes: [5, 6] }, + addNode(7), + setWidget(7, 'post-clear') + ]) + }) + + it('keeps a write to a node deleted and re-added in the same drain', () => { + expect( + orderMintedOperations([deleteNode(1), addNode(1), setWidget(1, 'x')]) + ).toEqual([deleteNode(1), addNode(1), setWidget(1, 'x')]) + }) + + it('never prunes a subgraph-interior widget write', () => { + const interior: GraphOperation = { + op: 'set_widget', + node_id: 2, + widget: 'seed', + value: 1, + old: 0, + path: ['2'], + inner_widget: 'seed' + } + expect(orderMintedOperations([interior, deleteNode(2)])).toEqual([ + deleteNode(2), + interior + ]) + }) +}) + +describe('createMintQueue', () => { + it('delivers one ordered batch per task after a double microtask', async () => { + const delivered: GraphOperation[][] = [] + const queue = createMintQueue((operations) => delivered.push(operations)) + + queue.enqueue([connect(41, 1, 2)]) + queueMicrotask(() => queue.enqueue([addNode(1), addNode(2)])) + expect(delivered).toEqual([]) + await Promise.resolve() + expect(delivered).toEqual([]) + await Promise.resolve() + + expect(delivered).toEqual([[addNode(1), addNode(2), connect(41, 1, 2)]]) + }) + + it('prunes the write a same-drain delete orphaned', async () => { + const delivered: GraphOperation[][] = [] + const queue = createMintQueue((operations) => delivered.push(operations)) + + queue.enqueue([setWidget(2, 'x')]) + queue.enqueue([deleteNode(2)]) + await afterDrain() + + expect(delivered).toEqual([[deleteNode(2)]]) + }) + + it('flush delivers synchronously and the scheduled drain then finds nothing', async () => { + const delivered: GraphOperation[][] = [] + const queue = createMintQueue((operations) => delivered.push(operations)) + + queue.enqueue([addNode(1)]) + queue.flush() + expect(delivered).toEqual([[addNode(1)]]) + await afterDrain() + + expect(delivered).toHaveLength(1) + }) + + it('separate tasks drain separately, in task order', async () => { + const delivered: GraphOperation[][] = [] + const queue = createMintQueue((operations) => delivered.push(operations)) + + queue.enqueue([addNode(1)]) + await afterDrain() + queue.enqueue([setWidget(1, 'x')]) + await afterDrain() + + expect(delivered).toEqual([[addNode(1)], [setWidget(1, 'x')]]) + }) +}) diff --git a/src/workbench/extensions/agent/crdt/mintQueue.ts b/src/workbench/extensions/agent/crdt/mintQueue.ts new file mode 100644 index 00000000000..d5b24353f96 --- /dev/null +++ b/src/workbench/extensions/agent/crdt/mintQueue.ts @@ -0,0 +1,106 @@ +/** + * The single ordered outbox behind the three mint ports. + * + * Each port mints on its own clock: the link and widget feeds fire + * synchronously inside the store action, while the layout store delivers a + * whole task's changes on ONE microtask. Raw mint order across ports is + * therefore NOT causal order - a same-task `createNode` + `registerLink` + * mints its connect before its add_node. Rather than racing per-port + * microtasks against the store's, every port enqueues here and one drain + * (a double microtask from the first enqueue: strictly after the layout + * store's flush and the link port's placement flush, both single-microtask) + * emits the task's ops in dependency order: + * + * 1. structural ops (add_node / delete_node / clear) in layout-store order, + * which IS causal for that class (one store, one queue); + * 2. connect / set_widget in mint order (synchronous feeds, causal within + * the class), which can only depend on nodes rule 1 already placed. + * + * A connect or top-level set_widget naming a node that the same drain + * deletes (delete_node, or a clear's removed_nodes) and does not re-add is + * dropped: rule 1 would land it after the delete, and the local graph + * already lacks the node, so doc and graph agree without it - the same + * argument as the link port's cancelPlacement. Interior set_widget (carries + * `path`) addresses a subgraph definition, not a root node, and is never + * pruned. + */ +import type { GraphOperation } from './graphOperations' + +export interface MintQueue { + /** Port-facing inbox; the drain is scheduled by the first call of a task. */ + enqueue(operations: GraphOperation[]): void + /** Deliver everything queued right now (the detach path). */ + flush(): void +} + +type StructuralOperation = Extract< + GraphOperation, + { op: 'add_node' | 'delete_node' | 'clear' } +> + +function isStructural( + operation: GraphOperation +): operation is StructuralOperation { + return ( + operation.op === 'add_node' || + operation.op === 'delete_node' || + operation.op === 'clear' + ) +} + +/** Pure ordering + pruning of one drain's worth of minted operations. */ +export function orderMintedOperations( + operations: GraphOperation[] +): GraphOperation[] { + const structural = operations.filter(isStructural) + const dependent = operations.filter((operation) => !isStructural(operation)) + const removed = new Set() + for (const operation of structural) { + if (operation.op === 'add_node') removed.delete(String(operation.node_id)) + else if (operation.op === 'delete_node') + removed.add(String(operation.node_id)) + else for (const id of operation.removed_nodes) removed.add(String(id)) + } + const gone = (nodeId: string | number): boolean => { + return removed.has(String(nodeId)) + } + const kept = dependent.filter((operation) => { + if (operation.op === 'connect') { + return !gone(operation.from_node) && !gone(operation.to_node) + } + if (operation.path == null) return !gone(operation.node_id) + return true + }) + return [...structural, ...kept] +} + +export function createMintQueue( + deliver: (operations: GraphOperation[]) => void +): MintQueue { + let queued: GraphOperation[] = [] + let drainScheduled = false + + function drain(): void { + drainScheduled = false + if (queued.length === 0) return + const batch = queued + queued = [] + const ordered = orderMintedOperations(batch) + if (ordered.length > 0) deliver(ordered) + } + + return { + enqueue(operations) { + if (operations.length === 0) return + queued.push(...operations) + if (drainScheduled) return + drainScheduled = true + // Double microtask: the layout store flushes on one, the link port's + // placement window closes on one; this drain must see both. + queueMicrotask(() => queueMicrotask(drain)) + }, + flush() { + drain() + } + } +} diff --git a/src/workbench/extensions/agent/crdt/opSender.test.ts b/src/workbench/extensions/agent/crdt/opSender.test.ts index 4e1cfaf7b23..08b77dd14ce 100644 --- a/src/workbench/extensions/agent/crdt/opSender.test.ts +++ b/src/workbench/extensions/agent/crdt/opSender.test.ts @@ -2,7 +2,7 @@ import type { Op } from '@comfyorg/comfy-multi-player' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { GraphOperation } from './graphOperations' -import { createOpSender } from './opSender' +import { createOpSender, toOpsResultView } from './opSender' import type { BatchOutcome, OpsResultView } from './opSender' const WORKFLOW = 'wf-1' @@ -399,6 +399,181 @@ describe('createOpSender', () => { expect(settled[0].state).toBe('acknowledged') }) + it('normalizes shipped doc_ops_result failed object and array shapes', () => { + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failed: { index: 0, op: { op_id: 'a'.repeat(32) } } + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'a'.repeat(32), index: 0 }, + failureOpIds: ['a'.repeat(32)] + }) + + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failed: [{ index: 0 }, { op_id: 'b'.repeat(32) }] + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'b'.repeat(32) }, + failureOpIds: ['b'.repeat(32)] + }) + }) + + it('preserves a canonical failure over a derived one, and collects every failed op_id', () => { + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'c'.repeat(32) }, + failed: [{ op_id: 'd'.repeat(32) }] + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'c'.repeat(32) }, + failureOpIds: ['c'.repeat(32), 'd'.repeat(32)] + }) + + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failed: [{ op_id: 'e'.repeat(32) }, { op_id: 'f'.repeat(32) }] + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'e'.repeat(32) }, + failureOpIds: ['e'.repeat(32), 'f'.repeat(32)] + }) + }) + + it('threads the host failure code, message and index through the view', () => { + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failed: { + index: 2, + op_id: 'a'.repeat(32), + code: 'op_rejected', + message: 'unknown node 7' + } + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { + op_id: 'a'.repeat(32), + index: 2, + code: 'op_rejected', + message: 'unknown node 7' + }, + failureOpIds: ['a'.repeat(32)] + }) + + // The canonical failure's reason wins over a legacy entry's and the + // frame's top-level code; each field is only taken when on-type. + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + code: 'frame_code', + message: 'frame message', + failure: { op_id: 'c'.repeat(32), code: 'lww_dropped', index: '0' }, + failed: [{ op_id: 'd'.repeat(32), code: 'legacy', message: 'legacy' }] + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { + op_id: 'c'.repeat(32), + code: 'lww_dropped', + message: 'legacy' + }, + failureOpIds: ['c'.repeat(32), 'd'.repeat(32)] + }) + + // A rejection that names no op still carries its reason (anonymous + // settle keeps working: no failureOpIds). + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + code: 'batch_too_large', + message: 'too many ops' + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { code: 'batch_too_large', message: 'too many ops' } + }) + + // A successful frame's stray code is not a failure. + expect( + toOpsResultView({ ok: true, applied: ['x'], skipped: [], code: 'noop' }) + ).toEqual({ ok: true, applied: ['x'], skipped: [] }) + }) + + it('a canonical empty-list rejection with no failed entries settles as anonymous', () => { + expect( + toOpsResultView({ ok: false, applied: [], skipped: [], failed: [] }) + ).toEqual({ + ok: false, + applied: [], + skipped: [] + }) + }) + + it('reads only a literal true as success and keeps only string op ids', () => { + expect( + toOpsResultView({ + ok: 'false', + applied: ['a'.repeat(32), 7, null], + skipped: [{ op_id: 'b'.repeat(32) }] + }) + ).toEqual({ + ok: false, + applied: ['a'.repeat(32)], + skipped: [] + }) + }) + + it('returns a safe empty view for a null or undefined doc_ops_result detail', () => { + expect(toOpsResultView(null)).toEqual({ + ok: false, + applied: [], + skipped: [] + }) + expect(toOpsResultView(undefined)).toEqual({ + ok: false, + applied: [], + skipped: [] + }) + }) + it('an identified failure for other ops never settles the in-flight batch', () => { sender.enqueue([addNode(1)]) @@ -412,6 +587,30 @@ describe('createOpSender', () => { expect(settled).toHaveLength(0) }) + it('a legacy failed id matching the in-flight batch settles it even under a foreign canonical op_id', () => { + sender.enqueue([addNode(1)]) + const own = sent[0].ops[0].op_id + + resultListener?.( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'ffff'.repeat(8), code: 'op_rejected' }, + failed: [{ op_id: own, code: 'op_rejected', message: 'rejected' }] + }) + ) + + expect(settled).toHaveLength(1) + expect(settled[0]).toMatchObject({ + state: 'acknowledged', + result: { + failure: { op_id: 'ffff'.repeat(8), code: 'op_rejected' }, + failureOpIds: ['ffff'.repeat(8), own] + } + }) + }) + it('idle late results drain the stale credits so a fresh batch can settle anonymously', () => { sender.enqueue([addNode(1)]) vi.advanceTimersByTime(10_000) diff --git a/src/workbench/extensions/agent/crdt/opSender.ts b/src/workbench/extensions/agent/crdt/opSender.ts index eb171e9be5e..34f43195c26 100644 --- a/src/workbench/extensions/agent/crdt/opSender.ts +++ b/src/workbench/extensions/agent/crdt/opSender.ts @@ -29,8 +29,119 @@ export interface OpsResultView { ok: boolean applied: string[] skipped: string[] - /** Failed-batch diagnostics when the host provides them; `op_id` correlates an otherwise empty-list failure to its batch. */ - failure?: { op_id?: string } + /** + * Failed-batch diagnostics when the host provides them. `op_id` correlates + * an otherwise empty-list failure to its batch; `code`, `message` and + * `index` are the host's own reason, threaded through verbatim so the + * settled outcome (dev panel, telemetry) can say WHY a batch failed rather + * than only that it did. + */ + failure?: OpsFailureView + /** Every `op_id` found in the host's failure payload (canonical `failure` first, then `failed`), for matching against an in-flight batch's op-id set rather than trusting a single arbitrary pick. */ + failureOpIds?: string[] +} + +interface OpsFailureView { + op_id?: string + /** Wire `DocOpFailure.code` (e.g. `op_rejected`). */ + code?: string + message?: string + /** Position of the failing op within the batch, when the host reports one. */ + index?: number +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' +} + +function failureOpId(value: unknown): string | undefined { + if (!isRecord(value)) return undefined + if (typeof value.op_id === 'string') return value.op_id + const nested = value.op + if (isRecord(nested) && typeof nested.op_id === 'string') return nested.op_id + return undefined +} + +/** The host's `failed` payload as a list: absent, one object, or an array. */ +function failedEntries(failed: unknown): unknown[] { + if (Array.isArray(failed)) return failed + return failed === undefined ? [] : [failed] +} + +/** All `op_id`s findable across the host's `failed` payload, in wire order. */ +function allFailureOpIds(failed: unknown): string[] { + return failedEntries(failed) + .map(failureOpId) + .filter((id): id is string => id !== undefined) +} + +/** A host id list, keeping only the `op_id` strings the sender can match on. */ +function opIdList(value: unknown): string[] { + if (!Array.isArray(value)) return [] + return value.filter((entry): entry is string => typeof entry === 'string') +} + +/** `code` / `message` / `index` from one host failure object, dropping anything off-type. */ +function failureDiagnostics(value: unknown): Omit { + if (!isRecord(value)) return {} + return { + ...(typeof value.code === 'string' && { code: value.code }), + ...(typeof value.message === 'string' && { message: value.message }), + ...(typeof value.index === 'number' && { index: value.index }) + } +} + +/** + * Normalize a `doc_ops_result` detail of ANY shape (the bridge forwards the + * frame client's parsed data, but the event contract is `unknown`) into the + * sender's view. A canonical `failure` from the host is authoritative for + * the single correlating `op_id`; `failed` (object or array, the shipped PoC + * shapes) contributes every further op_id so a batch can settle on any of + * them. Diagnostics come from the canonical failure, else the `failed` entry + * that names an op, else the frame's top-level `code` / `message`. + */ +export function toOpsResultView(detail: unknown): OpsResultView { + if (!isRecord(detail)) { + return { ok: false, applied: [], skipped: [] } + } + const canonical = isRecord(detail.failure) ? detail.failure : undefined + const canonicalOpId = + typeof canonical?.op_id === 'string' ? canonical.op_id : undefined + const failedIds = allFailureOpIds(detail.failed) + const failureOpIds = + canonicalOpId !== undefined + ? [canonicalOpId, ...failedIds.filter((id) => id !== canonicalOpId)] + : failedIds + // Legacy diagnostics come from the entry that names an op (so index and + // op_id describe the same failure), else the first entry. + const legacy = failedEntries(detail.failed) + const legacyDiagnostics = + legacy.find((entry) => failureOpId(entry) !== undefined) ?? legacy[0] + const diagnostics = { + ...failureDiagnostics(detail), + ...failureDiagnostics(legacyDiagnostics), + ...failureDiagnostics(canonical) + } + const ok = detail.ok === true + // Diagnostics alone only describe a failure on a failed frame; a success + // frame's stray `code` is not one. + const hasFailure = + failureOpIds.length > 0 || (!ok && Object.keys(diagnostics).length > 0) + return { + ...(typeof detail.workflowId === 'string' && { + workflowId: detail.workflowId + }), + ok, + applied: opIdList(detail.applied), + skipped: opIdList(detail.skipped), + ...(hasFailure && { + failure: { + ...(failureOpIds.length > 0 && { op_id: failureOpIds[0] }), + ...diagnostics + } + }), + ...(failureOpIds.length > 0 && { failureOpIds }) + } } export interface OpSenderDeps { @@ -187,8 +298,12 @@ export function createOpSender(deps: OpSenderDeps): OpSender { if (staleAnonymousBudget > 0) staleAnonymousBudget-- return } - const identified = [...result.applied, ...result.skipped] - if (result.failure?.op_id) identified.push(result.failure.op_id) + const identified = [ + ...result.applied, + ...result.skipped, + ...(result.failureOpIds ?? + (result.failure?.op_id ? [result.failure.op_id] : [])) + ] if (identified.length > 0) { if (!identified.some((opId) => inFlight!.opIds.has(opId))) return settle({ state: 'acknowledged', ops: inFlight.ops, result }) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index e76af459ef3..e28920f914c 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -21,8 +21,7 @@ import type { MutationsForTarget } from './ecsFollowerAdapter' import { EcsFollowerAdapter } from './ecsFollowerAdapter' import type { GraphOperation } from './graphOperations' import { LayoutFollowerBridge } from './layoutFollowerBridge' -import type { OpsResultView } from './opSender' -import { createOpSender } from './opSender' +import { createOpSender, toOpsResultView } from './opSender' // FE-1902: the doc id is otherwise held only in memory (set on turn ack), so a // panel remount loses the binding until the NEXT turn ack. Persist it per-tab @@ -250,16 +249,7 @@ export function useAgentCrdtFollower( onOpsResult(listener) { const handler: EventListener = (event) => { if (!(event instanceof CustomEvent)) return - const detail = event.detail as OpsResultView & { failed?: unknown } - listener({ - workflowId: detail.workflowId, - ok: detail.ok, - applied: detail.applied, - skipped: detail.skipped, - ...(detail.failed && typeof detail.failed === 'object' - ? { failure: detail.failed } - : {}) - }) + listener(toOpsResultView(event.detail)) } bridge.addEventListener('doc_ops_result', handler) return () => bridge.removeEventListener('doc_ops_result', handler)