From e5c75851847b02239c7fce80af464cd4218467f4 Mon Sep 17 00:00:00 2001 From: relaunch-gap-fe2157-rejection-telemetry-c17 Date: Sat, 12 Sep 2026 05:53:12 +0000 Subject: [PATCH 1/5] test(agent): cover tab open/switch/close/remount subscription lifetime (FE-2158) Adds a regression test for the useAgentCrdtFollower composable driving the sequence a real workflow tab strip produces: open tab A, switch to tab B (A goes inactive), close tab A (panel unmounts), then unmount+remount the panel for tab B. Asserts the net live-subscription count across bridge instances never exceeds one and that a doc_update frame stamped for a workflow other than the one currently bound is never applied (no cross-workflow projection), including after a stale bridge from a closed tab is dispatched a late frame. Verified as a real regression guard: removing the workflowId check in onUpdate's skip condition makes this test fail (applyFrame called with a frame from the wrong workflow); restored before committing. Linear: FE-2158 (tab/lifetime child). --- .../extensions/agent/crdt/tabLifetime.test.ts | 308 ++++++++++++++++++ 1 file changed, 308 insertions(+) create mode 100644 src/workbench/extensions/agent/crdt/tabLifetime.test.ts diff --git a/src/workbench/extensions/agent/crdt/tabLifetime.test.ts b/src/workbench/extensions/agent/crdt/tabLifetime.test.ts new file mode 100644 index 00000000000..55efa2be5cf --- /dev/null +++ b/src/workbench/extensions/agent/crdt/tabLifetime.test.ts @@ -0,0 +1,308 @@ +/** + * FE-2158 (tab/lifetime child) — regression coverage for the workflow-tab + * lifecycle around `useAgentCrdtFollower`: open a tab, switch away, close it, + * remount the panel, and verify the composable never accumulates more than + * one LIVE subscription and never projects a frame stamped for a workflow + * other than the one currently bound. + * + * This mirrors the mocking shape in `crossWorkflowPending.test.ts` (same + * fake bridge/client/adapter doubles) but drives the sequence a real tab + * strip produces: mount (open tab A) -> switch to tab B (A goes inactive, + * B active) -> close tab A (unrelated to B's binding) -> unmount + remount + * the panel (simulates a panel remount while B stays the active tab). + */ +import type { Op } from '@comfyorg/comfy-multi-player' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent, nextTick, ref } from 'vue' +import type { Ref } from 'vue' + +import type { GraphMutations } from '@/core/graph/graphMutations' +import { render } from '@testing-library/vue' + +const bridgeState = vi.hoisted(() => { + const transport = { up: true } + class FakeBridge extends EventTarget { + subscribe = vi.fn((workflowId: string) => { + if (!transport.up) return + this.subscribedWorkflowId = workflowId + this.lastSequence = 0 + }) + + unsubscribe = vi.fn(() => { + this.subscribedWorkflowId = null + }) + + resubscribe = vi.fn() + reconcile = vi.fn() + destroy = vi.fn() + subscribedWorkflowId: string | null = null + lastSequence = 0 + follower = { + updatesApplied: 0, + doc: { + getMap: () => ({ toJSON: () => ({}) }) + } + } + } + + return { + FakeBridge, + instances: [] as InstanceType[], + current: null as InstanceType | null, + transport + } +}) + +const clientState = vi.hoisted(() => ({ + destroy: vi.fn(), + transportUp: true, + sent: [] as Array<{ workflowId: string; tab: string; ops: Op[] }>, + sendOps: vi.fn((workflowId: string, tab: string, ops: Op[]) => { + if (!clientState.transportUp) return false + clientState.sent.push({ workflowId, tab, ops }) + return true + }) +})) + +const adapterState = vi.hoisted(() => ({ + bind: vi.fn(), + unbind: vi.fn(), + applyFrame: vi.fn(() => true), + clearForReset: vi.fn(), + discardPending: vi.fn(), + destroy: vi.fn() +})) + +const devLogState = vi.hoisted(() => ({ + recordDevEvent: vi.fn() +})) + +const apiState = vi.hoisted(() => { + const target = new EventTarget() + return { + target, + api: { + socket: { readyState: 1, send: vi.fn() }, + addCustomEventListener: vi.fn(), + removeCustomEventListener: vi.fn(), + addEventListener: (type: string, listener: EventListener) => + target.addEventListener(type, listener), + removeEventListener: vi.fn((type: string, listener: EventListener) => + target.removeEventListener(type, listener) + ) + } + } +}) + +vi.mock(import('./layoutFollowerBridge'), () => ({ + LayoutFollowerBridge: class { + constructor() { + const bridge = new bridgeState.FakeBridge() + bridgeState.current = bridge + bridgeState.instances.push(bridge) + return bridge + } + } +})) + +vi.mock(import('./docFrameClient'), () => ({ + DocFrameClient: class { + destroy = clientState.destroy + sendOps = clientState.sendOps + } +})) + +vi.mock(import('./ecsFollowerAdapter'), () => ({ + EcsFollowerAdapter: class { + bind = adapterState.bind + unbind = adapterState.unbind + applyFrame = adapterState.applyFrame + clearForReset = adapterState.clearForReset + discardPending = adapterState.discardPending + destroy = adapterState.destroy + } +})) + +vi.mock(import('./devPanelLog'), () => ({ + recordDevEvent: devLogState.recordDevEvent +})) + +vi.mock(import('@/scripts/api'), () => ({ api: apiState.api })) +vi.mock(import('@/scripts/app'), () => ({ + app: { graph: null, canvas: null } +})) + +import { useAgentCrdtFollower } from './useAgentCrdtFollower' +import type { + AgentCrdtOutcomeCounters, + AgentCrdtStatus +} from './useAgentCrdtFollower' + +const graphMutations = {} as GraphMutations + +/** + * Mounts a panel instance the way `AgentPanelRoot.vue` does: a reactive + * `workflowId` for the tab this panel is bound to, and an `isTargetActive` + * flag that flips false when the tab strip switches away from this tab. + * Returns handles for driving tab-switch / tab-close / panel-remount. + */ +function mountPanel( + initialWorkflowId: string, + initialActive: boolean +): { + unmount: () => void + workflowId: Ref + isActive: Ref + outcomes: () => AgentCrdtOutcomeCounters +} { + const workflowId = ref(initialWorkflowId) + const isActive = ref(initialActive) + let exposedStatus!: () => AgentCrdtStatus + const host = defineComponent({ + setup() { + const { status } = useAgentCrdtFollower( + workflowId, + graphMutations, + () => null, + isActive + ) + exposedStatus = () => status.value as AgentCrdtStatus + return () => null + } + }) + const { unmount } = render(host) + return { + unmount, + workflowId, + isActive, + outcomes: () => exposedStatus().outcomes + } +} + +/** Net count of subscriptions currently believed live across every bridge + * instance constructed so far. A bridge counts as live only if it has ever + * subscribed, has not since unsubscribed (the active->inactive edge), and has + * not been torn down (`destroy()`, the panel-unmount teardown path — which + * releases the transport without a separate `unsubscribe()` call). */ +function liveSubscriptionCount(): number { + return bridgeState.instances.filter( + (instance) => + instance.subscribe.mock.calls.length > 0 && + instance.unsubscribe.mock.calls.length === 0 && + instance.destroy.mock.calls.length === 0 + ).length +} + +function bridgeFor( + index: number +): InstanceType<(typeof bridgeState)['FakeBridge']> { + const instance = bridgeState.instances.at(index) + if (!instance) throw new Error(`no bridge constructed at index ${index}`) + return instance +} + +function dispatchDocUpdate( + bridge: InstanceType<(typeof bridgeState)['FakeBridge']>, + workflowId: string, + seq: number +): void { + bridge.dispatchEvent( + new CustomEvent('doc_update', { + detail: { workflowId, seq, update: new Uint8Array() } + }) + ) +} + +describe('FE-2158 tab lifetime: open / switch / close / remount', () => { + beforeEach(() => { + bridgeState.current = null + bridgeState.instances = [] + bridgeState.transport.up = true + clientState.transportUp = true + clientState.sent = [] + clientState.sendOps.mockClear() + adapterState.bind.mockClear() + adapterState.unbind.mockClear() + adapterState.applyFrame.mockClear() + adapterState.destroy.mockClear() + devLogState.recordDevEvent.mockClear() + }) + + it('leaves exactly one live subscription and applies no cross-workflow frame after open, switch, close, and remount', async () => { + // 1. Open tab A: panel A mounts active and bound to workflow A. + const panelA = mountPanel('wf-a', true) + await nextTick() + expect(bridgeState.instances).toHaveLength(1) + expect(bridgeFor(0).subscribe).toHaveBeenCalledWith('wf-a') + expect(liveSubscriptionCount()).toBe(1) + + // 2. Open tab B and switch to it: the tab strip flips A inactive and + // mounts/activates B. A's composable unsubscribes on the active->false + // edge; B's composable (a second panel instance, same as a second tab + // binding a follower) subscribes to workflow B. + panelA.isActive.value = false + await nextTick() + expect(bridgeFor(0).unsubscribe).toHaveBeenCalledTimes(1) + expect(liveSubscriptionCount()).toBe(0) + + const panelB = mountPanel('wf-b', true) + await nextTick() + expect(bridgeState.instances).toHaveLength(2) + expect(bridgeFor(1).subscribe).toHaveBeenCalledWith('wf-b') + expect(liveSubscriptionCount()).toBe(1) + + // 3. Close tab A: its panel unmounts. Teardown must fully release the + // stale bridge (no double-unsubscribe, no leaked listener) and must not + // touch B's live subscription count. + panelA.unmount() + await nextTick() + expect(adapterState.destroy).toHaveBeenCalledTimes(1) + expect(liveSubscriptionCount()).toBe(1) + + // A's bridge is stale post-close: a frame arriving late for workflow A + // (e.g. an in-flight server frame that raced the close) must not be + // projected by B's adapter. Dispatch it on A's now-destroyed bridge to + // characterize that a post-teardown frame is inert, then dispatch a + // same-shaped frame on B's live bridge tagged with A's workflow id to + // characterize the cross-workflow guard on the live path. + dispatchDocUpdate(bridgeFor(0), 'wf-a', 99) + dispatchDocUpdate(bridgeFor(1), 'wf-a', 1) + await nextTick() + expect(adapterState.applyFrame).not.toHaveBeenCalled() + expect(panelB.outcomes().applied).toBe(0) + expect(panelB.outcomes().skipped).toBeGreaterThan(0) + + // A same-workflow frame on B's own bridge DOES apply, proving the guard + // above discriminated on workflow id and not on some broader silence. + dispatchDocUpdate(bridgeFor(1), 'wf-b', 2) + await nextTick() + expect(adapterState.applyFrame).toHaveBeenCalledTimes(1) + expect(panelB.outcomes().applied).toBe(1) + + // 4. Remount the panel for workflow B (simulates a panel unmount + + // immediate remount while tab B stays the active tab, e.g. an extension + // reload). The old bridge must be fully torn down and exactly one new + // live subscription must exist afterward — never zero (lost binding), + // never two (leaked prior subscription). + panelB.unmount() + await nextTick() + expect(liveSubscriptionCount()).toBe(0) + + const panelBRemounted = mountPanel('wf-b', true) + await nextTick() + expect(bridgeState.instances).toHaveLength(3) + expect(bridgeFor(2).subscribe).toHaveBeenCalledWith('wf-b') + expect(liveSubscriptionCount()).toBe(1) + + // A stale frame for the closed tab A workflow still must not land on the + // remounted panel. + dispatchDocUpdate(bridgeFor(2), 'wf-a', 100) + await nextTick() + expect(panelBRemounted.outcomes().applied).toBe(0) + expect(panelBRemounted.outcomes().skipped).toBeGreaterThan(0) + + panelBRemounted.unmount() + await nextTick() + expect(liveSubscriptionCount()).toBe(0) + }) +}) From c6c445d1424b365d2b8ad9b647a575be5bf20eec Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 12 Sep 2026 22:02:54 -0700 Subject: [PATCH 2/5] test(agent-crdt): type the mutations fixture and assert panel A stays silent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two CodeRabbit findings, both verified before applying. 1. graphMutations was `{} as GraphMutations`. GraphMutations declares six methods, so adding a seventh would compile against an empty object and the fixture would silently not exercise it. Now a typed literal with all six as vi.fn(() => true), which fails to compile when the contract changes. 2. The post-teardown dispatch asserted only on panel B. A LEAKED panel A listener would receive the stale wf-a frame, skip it, and leave Bs counters untouched — so the test passed through exactly the leak it exists to catch. Captures As counters before the dispatch and asserts they are unchanged; a skip would still prove the listener was alive, so equality is the right bar, not "skipped stayed 0". As status closure survives unmount, so the read is valid post-close. Verified the new assertion can fail: negating it produces AssertionError, and Bs skipped > 0 on the same tick proves the counters are live rather than frozen. --- .../extensions/agent/crdt/tabLifetime.test.ts | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/workbench/extensions/agent/crdt/tabLifetime.test.ts b/src/workbench/extensions/agent/crdt/tabLifetime.test.ts index 55efa2be5cf..c89caef642d 100644 --- a/src/workbench/extensions/agent/crdt/tabLifetime.test.ts +++ b/src/workbench/extensions/agent/crdt/tabLifetime.test.ts @@ -138,7 +138,16 @@ import type { AgentCrdtStatus } from './useAgentCrdtFollower' -const graphMutations = {} as GraphMutations +// Every method the interface declares, so a contract change fails to compile +// here instead of silently leaving an empty object satisfying the cast. +const graphMutations: GraphMutations = { + batch: vi.fn(() => true), + addNode: vi.fn(() => true), + setWidget: vi.fn(() => true), + connect: vi.fn(() => true), + deleteNode: vi.fn(() => true), + clearSemanticGraph: vi.fn(() => true) +} /** * Mounts a panel instance the way `AgentPanelRoot.vue` does: a reactive @@ -265,12 +274,21 @@ describe('FE-2158 tab lifetime: open / switch / close / remount', () => { // characterize that a post-teardown frame is inert, then dispatch a // same-shaped frame on B's live bridge tagged with A's workflow id to // characterize the cross-workflow guard on the live path. + // Captured before the dispatch: every assertion below is about panel B, so + // without this a LEAKED panel A listener would receive the stale frame, + // skip it, and leave B's counters untouched — the test would pass through + // exactly the leak it exists to catch. A's status closure survives unmount. + const panelAAfterClose = { ...panelA.outcomes() } + dispatchDocUpdate(bridgeFor(0), 'wf-a', 99) dispatchDocUpdate(bridgeFor(1), 'wf-a', 1) await nextTick() expect(adapterState.applyFrame).not.toHaveBeenCalled() expect(panelB.outcomes().applied).toBe(0) expect(panelB.outcomes().skipped).toBeGreaterThan(0) + // A saw nothing at all — neither applied nor skipped. A skip would still + // mean its listener was alive. + expect(panelA.outcomes()).toEqual(panelAAfterClose) // A same-workflow frame on B's own bridge DOES apply, proving the guard // above discriminated on workflow id and not on some broader silence. From 8714384878dca7429323072ff35c17d73f67182a Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 12 Sep 2026 23:02:38 -0700 Subject: [PATCH 3/5] test(agent-crdt): fold the tab-lifetime case into its owning suite MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses DrJKL review. Verified each claim before acting. P1 — the case did not exercise the lifecycle the app uses. AgentPanelRoot.vue :492 creates ONE follower driven by reactive boundWorkflowId and isBoundWorkflowActive; the old test mounted two panels, so a broken direct A-to-B retarget on the real singleton would have stayed green. The case now lives in useAgentCrdtFollower.test.ts and drives a single follower through A -> inactive -> B -> unmount via that suites mountFollower refs. P2 — the file rebuilt bridge, client, adapter, API and mount fakes the owning suite already maintains, and that suite already covers inactive suspension, wrong-workflow filtering and teardown. Deleted tabLifetime.test.ts rather than keeping a third fake contract. That also removes the inert FakeBridge.destroy counting, the untyped vi.mock factories, the unread bridgeState .current, the redundant mockClear calls (vite.config.mts sets mockReset), the unnecessary status casts, and the narration — all of which were properties of that file. Kept as the non-obvious part: the stale wf-a frame must be counted and skipped rather than applied, paired with a wf-b frame that does apply, so the filter is shown to discriminate on workflow id rather than having gone silent. Verified: full crdt suite 34 files / 489 tests green after deletion; the retarget assertion fails when mutated to expect wf-a, so it observes the retarget rather than passing vacuously. --- .../extensions/agent/crdt/tabLifetime.test.ts | 326 ------------------ .../agent/crdt/useAgentCrdtFollower.test.ts | 35 ++ 2 files changed, 35 insertions(+), 326 deletions(-) delete mode 100644 src/workbench/extensions/agent/crdt/tabLifetime.test.ts diff --git a/src/workbench/extensions/agent/crdt/tabLifetime.test.ts b/src/workbench/extensions/agent/crdt/tabLifetime.test.ts deleted file mode 100644 index c89caef642d..00000000000 --- a/src/workbench/extensions/agent/crdt/tabLifetime.test.ts +++ /dev/null @@ -1,326 +0,0 @@ -/** - * FE-2158 (tab/lifetime child) — regression coverage for the workflow-tab - * lifecycle around `useAgentCrdtFollower`: open a tab, switch away, close it, - * remount the panel, and verify the composable never accumulates more than - * one LIVE subscription and never projects a frame stamped for a workflow - * other than the one currently bound. - * - * This mirrors the mocking shape in `crossWorkflowPending.test.ts` (same - * fake bridge/client/adapter doubles) but drives the sequence a real tab - * strip produces: mount (open tab A) -> switch to tab B (A goes inactive, - * B active) -> close tab A (unrelated to B's binding) -> unmount + remount - * the panel (simulates a panel remount while B stays the active tab). - */ -import type { Op } from '@comfyorg/comfy-multi-player' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { defineComponent, nextTick, ref } from 'vue' -import type { Ref } from 'vue' - -import type { GraphMutations } from '@/core/graph/graphMutations' -import { render } from '@testing-library/vue' - -const bridgeState = vi.hoisted(() => { - const transport = { up: true } - class FakeBridge extends EventTarget { - subscribe = vi.fn((workflowId: string) => { - if (!transport.up) return - this.subscribedWorkflowId = workflowId - this.lastSequence = 0 - }) - - unsubscribe = vi.fn(() => { - this.subscribedWorkflowId = null - }) - - resubscribe = vi.fn() - reconcile = vi.fn() - destroy = vi.fn() - subscribedWorkflowId: string | null = null - lastSequence = 0 - follower = { - updatesApplied: 0, - doc: { - getMap: () => ({ toJSON: () => ({}) }) - } - } - } - - return { - FakeBridge, - instances: [] as InstanceType[], - current: null as InstanceType | null, - transport - } -}) - -const clientState = vi.hoisted(() => ({ - destroy: vi.fn(), - transportUp: true, - sent: [] as Array<{ workflowId: string; tab: string; ops: Op[] }>, - sendOps: vi.fn((workflowId: string, tab: string, ops: Op[]) => { - if (!clientState.transportUp) return false - clientState.sent.push({ workflowId, tab, ops }) - return true - }) -})) - -const adapterState = vi.hoisted(() => ({ - bind: vi.fn(), - unbind: vi.fn(), - applyFrame: vi.fn(() => true), - clearForReset: vi.fn(), - discardPending: vi.fn(), - destroy: vi.fn() -})) - -const devLogState = vi.hoisted(() => ({ - recordDevEvent: vi.fn() -})) - -const apiState = vi.hoisted(() => { - const target = new EventTarget() - return { - target, - api: { - socket: { readyState: 1, send: vi.fn() }, - addCustomEventListener: vi.fn(), - removeCustomEventListener: vi.fn(), - addEventListener: (type: string, listener: EventListener) => - target.addEventListener(type, listener), - removeEventListener: vi.fn((type: string, listener: EventListener) => - target.removeEventListener(type, listener) - ) - } - } -}) - -vi.mock(import('./layoutFollowerBridge'), () => ({ - LayoutFollowerBridge: class { - constructor() { - const bridge = new bridgeState.FakeBridge() - bridgeState.current = bridge - bridgeState.instances.push(bridge) - return bridge - } - } -})) - -vi.mock(import('./docFrameClient'), () => ({ - DocFrameClient: class { - destroy = clientState.destroy - sendOps = clientState.sendOps - } -})) - -vi.mock(import('./ecsFollowerAdapter'), () => ({ - EcsFollowerAdapter: class { - bind = adapterState.bind - unbind = adapterState.unbind - applyFrame = adapterState.applyFrame - clearForReset = adapterState.clearForReset - discardPending = adapterState.discardPending - destroy = adapterState.destroy - } -})) - -vi.mock(import('./devPanelLog'), () => ({ - recordDevEvent: devLogState.recordDevEvent -})) - -vi.mock(import('@/scripts/api'), () => ({ api: apiState.api })) -vi.mock(import('@/scripts/app'), () => ({ - app: { graph: null, canvas: null } -})) - -import { useAgentCrdtFollower } from './useAgentCrdtFollower' -import type { - AgentCrdtOutcomeCounters, - AgentCrdtStatus -} from './useAgentCrdtFollower' - -// Every method the interface declares, so a contract change fails to compile -// here instead of silently leaving an empty object satisfying the cast. -const graphMutations: GraphMutations = { - batch: vi.fn(() => true), - addNode: vi.fn(() => true), - setWidget: vi.fn(() => true), - connect: vi.fn(() => true), - deleteNode: vi.fn(() => true), - clearSemanticGraph: vi.fn(() => true) -} - -/** - * Mounts a panel instance the way `AgentPanelRoot.vue` does: a reactive - * `workflowId` for the tab this panel is bound to, and an `isTargetActive` - * flag that flips false when the tab strip switches away from this tab. - * Returns handles for driving tab-switch / tab-close / panel-remount. - */ -function mountPanel( - initialWorkflowId: string, - initialActive: boolean -): { - unmount: () => void - workflowId: Ref - isActive: Ref - outcomes: () => AgentCrdtOutcomeCounters -} { - const workflowId = ref(initialWorkflowId) - const isActive = ref(initialActive) - let exposedStatus!: () => AgentCrdtStatus - const host = defineComponent({ - setup() { - const { status } = useAgentCrdtFollower( - workflowId, - graphMutations, - () => null, - isActive - ) - exposedStatus = () => status.value as AgentCrdtStatus - return () => null - } - }) - const { unmount } = render(host) - return { - unmount, - workflowId, - isActive, - outcomes: () => exposedStatus().outcomes - } -} - -/** Net count of subscriptions currently believed live across every bridge - * instance constructed so far. A bridge counts as live only if it has ever - * subscribed, has not since unsubscribed (the active->inactive edge), and has - * not been torn down (`destroy()`, the panel-unmount teardown path — which - * releases the transport without a separate `unsubscribe()` call). */ -function liveSubscriptionCount(): number { - return bridgeState.instances.filter( - (instance) => - instance.subscribe.mock.calls.length > 0 && - instance.unsubscribe.mock.calls.length === 0 && - instance.destroy.mock.calls.length === 0 - ).length -} - -function bridgeFor( - index: number -): InstanceType<(typeof bridgeState)['FakeBridge']> { - const instance = bridgeState.instances.at(index) - if (!instance) throw new Error(`no bridge constructed at index ${index}`) - return instance -} - -function dispatchDocUpdate( - bridge: InstanceType<(typeof bridgeState)['FakeBridge']>, - workflowId: string, - seq: number -): void { - bridge.dispatchEvent( - new CustomEvent('doc_update', { - detail: { workflowId, seq, update: new Uint8Array() } - }) - ) -} - -describe('FE-2158 tab lifetime: open / switch / close / remount', () => { - beforeEach(() => { - bridgeState.current = null - bridgeState.instances = [] - bridgeState.transport.up = true - clientState.transportUp = true - clientState.sent = [] - clientState.sendOps.mockClear() - adapterState.bind.mockClear() - adapterState.unbind.mockClear() - adapterState.applyFrame.mockClear() - adapterState.destroy.mockClear() - devLogState.recordDevEvent.mockClear() - }) - - it('leaves exactly one live subscription and applies no cross-workflow frame after open, switch, close, and remount', async () => { - // 1. Open tab A: panel A mounts active and bound to workflow A. - const panelA = mountPanel('wf-a', true) - await nextTick() - expect(bridgeState.instances).toHaveLength(1) - expect(bridgeFor(0).subscribe).toHaveBeenCalledWith('wf-a') - expect(liveSubscriptionCount()).toBe(1) - - // 2. Open tab B and switch to it: the tab strip flips A inactive and - // mounts/activates B. A's composable unsubscribes on the active->false - // edge; B's composable (a second panel instance, same as a second tab - // binding a follower) subscribes to workflow B. - panelA.isActive.value = false - await nextTick() - expect(bridgeFor(0).unsubscribe).toHaveBeenCalledTimes(1) - expect(liveSubscriptionCount()).toBe(0) - - const panelB = mountPanel('wf-b', true) - await nextTick() - expect(bridgeState.instances).toHaveLength(2) - expect(bridgeFor(1).subscribe).toHaveBeenCalledWith('wf-b') - expect(liveSubscriptionCount()).toBe(1) - - // 3. Close tab A: its panel unmounts. Teardown must fully release the - // stale bridge (no double-unsubscribe, no leaked listener) and must not - // touch B's live subscription count. - panelA.unmount() - await nextTick() - expect(adapterState.destroy).toHaveBeenCalledTimes(1) - expect(liveSubscriptionCount()).toBe(1) - - // A's bridge is stale post-close: a frame arriving late for workflow A - // (e.g. an in-flight server frame that raced the close) must not be - // projected by B's adapter. Dispatch it on A's now-destroyed bridge to - // characterize that a post-teardown frame is inert, then dispatch a - // same-shaped frame on B's live bridge tagged with A's workflow id to - // characterize the cross-workflow guard on the live path. - // Captured before the dispatch: every assertion below is about panel B, so - // without this a LEAKED panel A listener would receive the stale frame, - // skip it, and leave B's counters untouched — the test would pass through - // exactly the leak it exists to catch. A's status closure survives unmount. - const panelAAfterClose = { ...panelA.outcomes() } - - dispatchDocUpdate(bridgeFor(0), 'wf-a', 99) - dispatchDocUpdate(bridgeFor(1), 'wf-a', 1) - await nextTick() - expect(adapterState.applyFrame).not.toHaveBeenCalled() - expect(panelB.outcomes().applied).toBe(0) - expect(panelB.outcomes().skipped).toBeGreaterThan(0) - // A saw nothing at all — neither applied nor skipped. A skip would still - // mean its listener was alive. - expect(panelA.outcomes()).toEqual(panelAAfterClose) - - // A same-workflow frame on B's own bridge DOES apply, proving the guard - // above discriminated on workflow id and not on some broader silence. - dispatchDocUpdate(bridgeFor(1), 'wf-b', 2) - await nextTick() - expect(adapterState.applyFrame).toHaveBeenCalledTimes(1) - expect(panelB.outcomes().applied).toBe(1) - - // 4. Remount the panel for workflow B (simulates a panel unmount + - // immediate remount while tab B stays the active tab, e.g. an extension - // reload). The old bridge must be fully torn down and exactly one new - // live subscription must exist afterward — never zero (lost binding), - // never two (leaked prior subscription). - panelB.unmount() - await nextTick() - expect(liveSubscriptionCount()).toBe(0) - - const panelBRemounted = mountPanel('wf-b', true) - await nextTick() - expect(bridgeState.instances).toHaveLength(3) - expect(bridgeFor(2).subscribe).toHaveBeenCalledWith('wf-b') - expect(liveSubscriptionCount()).toBe(1) - - // A stale frame for the closed tab A workflow still must not land on the - // remounted panel. - dispatchDocUpdate(bridgeFor(2), 'wf-a', 100) - await nextTick() - expect(panelBRemounted.outcomes().applied).toBe(0) - expect(panelBRemounted.outcomes().skipped).toBeGreaterThan(0) - - panelBRemounted.unmount() - await nextTick() - expect(liveSubscriptionCount()).toBe(0) - }) -}) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts index 1d366139f48..a84c8500ac5 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -278,6 +278,41 @@ describe('useAgentCrdtFollower', () => { }) }) + it('FE-2158: one follower retargets across a tab switch and releases on unmount', async () => { + // AgentPanelRoot.vue creates a SINGLE follower and drives it with the + // reactive boundWorkflowId / isBoundWorkflowActive. Exercising the switch + // as two mounted followers would leave a broken direct A-to-B retarget + // green, because no one follower would ever change workflow. + const { unmount, workflowId, isTargetActive, status } = + mountFollower('wf-a') + expect(bridge().subscribe).toHaveBeenLastCalledWith('wf-a') + + isTargetActive.value = false + await nextTick() + + workflowId.value = 'wf-b' + isTargetActive.value = true + await nextTick() + expect(bridge().subscribe).toHaveBeenLastCalledWith('wf-b') + + // A frame for the workflow this follower just left must be counted and + // dropped, never applied to the newly bound graph. + dispatchFrame('doc_update', { workflowId: 'wf-a', seq: 99 }) + expect(status().outcomes.applied).toBe(0) + expect(status().outcomes.skipped).toBeGreaterThan(0) + expect(adapterState.applyFrame).not.toHaveBeenCalled() + + // Control: the retarget really did bind B, so the filter above + // discriminated on workflow id rather than having gone silent. + dispatchFrame('doc_update', { workflowId: 'wf-b', seq: 1 }) + expect(status().outcomes.applied).toBe(1) + expect(adapterState.applyFrame).toHaveBeenCalledTimes(1) + + unmount() + await nextTick() + expect(bridge().unsubscribe).toHaveBeenCalled() + }) + it('FE-1902: persists a binding only once the server confirms it', () => { const { unmount } = mountFollower('wf-1') expect(persistedRecord()).toBeNull() From 3c36af2dc9a76a3a61225b3d8af9996c051c2f1f Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 3 Oct 2026 08:33:47 -0700 Subject: [PATCH 4/5] test(agent-crdt): cover follower remount lifetime --- .../agent/crdt/useAgentCrdtFollower.test.ts | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts index 2085c966fc0..0e6edf729dd 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -480,7 +480,7 @@ describe('useAgentCrdtFollower', () => { }) }) - it('FE-2158: one follower retargets across a tab switch and releases on unmount', async () => { + it('FE-2158: one follower retargets across a tab switch and releases across remount', async () => { // AgentPanelRoot.vue creates a SINGLE follower and drives it with the // reactive boundWorkflowId / isBoundWorkflowActive. Exercising the switch // as two mounted followers would leave a broken direct A-to-B retarget @@ -502,17 +502,33 @@ describe('useAgentCrdtFollower', () => { dispatchFrame('doc_update', { workflowId: 'wf-a', seq: 99 }) expect(status().outcomes.applied).toBe(0) expect(status().outcomes.skipped).toBeGreaterThan(0) - expect(adapterState.applyFrame).not.toHaveBeenCalled() + expect(projectionState.applyFrame).not.toHaveBeenCalled() // Control: the retarget really did bind B, so the filter above // discriminated on workflow id rather than having gone silent. dispatchFrame('doc_update', { workflowId: 'wf-b', seq: 1 }) expect(status().outcomes.applied).toBe(1) - expect(adapterState.applyFrame).toHaveBeenCalledTimes(1) + expect(projectionState.applyFrame).toHaveBeenCalledTimes(1) + const staleBridge = bridge() unmount() await nextTick() - expect(bridge().unsubscribe).toHaveBeenCalled() + expect(staleBridge.unsubscribe).toHaveBeenCalled() + + staleBridge.dispatchEvent( + new CustomEvent('doc_update', { + detail: { workflowId: 'wf-b', seq: 2 } + }) + ) + expect(projectionState.applyFrame).toHaveBeenCalledTimes(1) + + const remounted = mountFollower('wf-b') + expect(bridge()).not.toBe(staleBridge) + expect(bridge().subscribe).toHaveBeenCalledExactlyOnceWith('wf-b') + + dispatchFrame('doc_update', { workflowId: 'wf-b', seq: 2 }) + expect(projectionState.applyFrame).toHaveBeenCalledTimes(2) + remounted.unmount() }) it('FE-1902: persists a binding only once the server confirms it', () => { From 66e899c743eed75e156ba01b00611176232a3627 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 3 Oct 2026 08:48:03 -0700 Subject: [PATCH 5/5] test(agent-crdt): count live follower subscriptions --- .../agent/crdt/useAgentCrdtFollower.test.ts | 37 +++++++++++++++++-- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts index 0e6edf729dd..99ada0f358c 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -27,12 +27,32 @@ import type { GraphOperation } from './graphOperations' import type { BatchOutcome, OpSenderDeps } from './opSender' const bridgeState = vi.hoisted(() => { + const liveSubscriptions = new Map>() + let maxLiveSubscriptions = 0 + const countLiveSubscriptions = () => + [...liveSubscriptions.values()].reduce( + (count, workflows) => count + workflows.size, + 0 + ) + class FakeBridge extends EventTarget { - subscribe = vi.fn() - unsubscribe = vi.fn() + subscribe = vi.fn((workflowId: string) => { + // A bridge retargets its single subscription; concurrency is measured + // across bridge instances, not across its historical workflow ids. + liveSubscriptions.set(this, new Set([workflowId])) + maxLiveSubscriptions = Math.max( + maxLiveSubscriptions, + countLiveSubscriptions() + ) + }) + unsubscribe = vi.fn(() => { + liveSubscriptions.delete(this) + }) resubscribe = vi.fn() reconcile = vi.fn() - destroy = vi.fn() + destroy = vi.fn(() => { + liveSubscriptions.delete(this) + }) sendHumanOps = vi.fn() subscribedWorkflowId: string | null = 'wf-1' lastSequence = 41 @@ -45,7 +65,14 @@ const bridgeState = vi.hoisted(() => { } return { FakeBridge, - current: null as InstanceType | null + current: null as InstanceType | null, + get maxLiveSubscriptions() { + return maxLiveSubscriptions + }, + resetLiveSubscriptions() { + liveSubscriptions.clear() + maxLiveSubscriptions = 0 + } } }) @@ -245,6 +272,7 @@ describe('useAgentCrdtFollower', () => { useAgentPanelStore().enabled = true sessionStorage.clear() bridgeState.current = null + bridgeState.resetLiveSubscriptions() clientState.transport = null projectionState.applyFrame .mockReset() @@ -529,6 +557,7 @@ describe('useAgentCrdtFollower', () => { dispatchFrame('doc_update', { workflowId: 'wf-b', seq: 2 }) expect(projectionState.applyFrame).toHaveBeenCalledTimes(2) remounted.unmount() + expect(bridgeState.maxLiveSubscriptions).toBeLessThanOrEqual(1) }) it('FE-1902: persists a binding only once the server confirms it', () => {