From fbb125ddc2402f85ff899afae21af35623fa1493 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 13:06:01 +0000 Subject: [PATCH] fix(agent): make agent panel teardown total (#20078) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to #20071: make the agent panel's unmount total, so no teardown step can be skipped by an earlier one throwing. `onBeforeUnmount`, ahead of the large unmount hook, so a throwing teardown step could no longer leave the layer id claimed in the module registry. Review ([thread](https://github.com/Comfy-Org/ComfyUI_frontend/pull/20071#discussion_r4176278309), raised by 4 of 8 reviewers) found that this rescues one victim and leaves the rest exposed, and the PR merged with the thread open and the fix deferred to a follow-up. This is that follow-up. A throw in `releaseCoachCompletionWaiters()`, `invalidateSubmission()`, `docOpMinter.detach()`, `restoreOpMinter.detach()`, `exitNodeSelectionMode()`, `stop()` or `setEditing`/`setCreating` still skips every later step in the same hook — including the PM-1575 `setCanvasSyncGate` reset, which the comment beside it calls the only thing standing between a turn resumed in the meantime and a torn-down follower's gate on the store singleton. The gate is not merely late in that case, it is never reset: a reverted-fix run of the new test records **zero** `setCanvasSyncGate` calls during unmount. It is also wider than one hook. No `app.config.errorHandler` is registered anywhere in the app, so Vue's `logError` re-throws outside production builds; the throw escapes `invokeArrayFns` and abandons the remaining `beforeUnmount` hooks (`attachment.cancelAllUploads()`) and the rest of `unmountComponent`, including `scope.stop()`. - **What**: every step of `AgentPanelRoot.vue`'s unmount now runs through a local `runPanelTeardown`, which reports a failing step as `failure_tearing_down_agent_panel` and continues to the next one. All three of the component's `onBeforeUnmount` hooks go through it, so no hook can abandon a later one either. Step order is unchanged. - **Steps are keyed, not positional**: the key rides on `tags.step`, because the error is swallowed now and the report is the only remaining signal that a release was skipped — telemetry has to be able to tell a `stopSession` failure (a leaked event-stream subscription and un-aborted turn recovery for the session) from a benign `clearCreatingTab` one. No key is integer-like, so `Object.entries` order is specified and insertion order stays the run order. Steps return `undefined` rather than `void` so an async step — whose rejection would escape the catch while still looking contained — fails to compile. The `reportError` call has its own try/catch, since it was the one call in the loop that could abort the teardown it was reporting on. - **Tests**: a new case arms `docOpMinter.detach()` to throw and asserts the PM-1575 gate is still reset to the always-safe default (`gate() === false`, `outcomeCount() === 0`); it fails on the primary assertion against `main` (`expected to be called once, but got 0 times`). The existing throwing-teardown case now asserts the error is *contained and reported* rather than escaping to Vue's handler, and also fails against `main`. A third case arms the reporter itself to throw and asserts the gate is still reset; it fails against an unguarded reporter. Both pre-existing cases assert the `step` tag. The minimap duplicate-free remount assertion from #20071 is unchanged. Four review findings came back on the first revision; three are fixed in 6234899 (async-step typing, the unguarded reporter, the undifferentiated `errorType`). The fourth — that several steps are themselves multi-release sequences with no internal guard — is real and is answered on the thread: it needs three small per-module changes rather than anything this call site can express, and `exitNodeSelectionMode()` in particular is re-entrant by design so splitting it at the call site is unsafe. This deliberately mirrors `runFollowerTeardown` in `crdt/useAgentCrdtFollower.ts` — same rationale, same report-and-continue shape — rather than sharing it, because that file is the CRDT follower's own teardown and its reporter is hard-coded to a different `errorType`. Say the word if you would rather have one shared helper and I will extract it. The second-order question the thread raises and this does not answer: registering an `app.config.errorHandler` would make unmount resilient app-wide instead of one component at a time. That is a global behavior change well outside a teardown fix, so it is not attempted here. --- .../extensions/agent/AgentPanelRoot.test.ts | 85 ++++++++++++- .../extensions/agent/AgentPanelRoot.vue | 112 ++++++++++++++---- 2 files changed, 170 insertions(+), 27 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 896589fb42d..c11130b5524 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -4340,11 +4340,17 @@ describe('AgentPanelRoot lifecycle', () => { }) first.unmount() - expect(errorHandler).toHaveBeenCalledWith( + // Contained and reported, not escaped: a step that throws must not reach + // Vue's error handling, which re-throws out of `invokeArrayFns` and would + // abandon the remaining hooks and the rest of `unmountComponent`. + expect(reportError).toHaveBeenCalledWith( expect.objectContaining({ message: 'teardown failed' }), - expect.anything(), - 'beforeUnmount hook' + expect.objectContaining({ + errorType: 'failure_tearing_down_agent_panel', + tags: { step: 'clearCreatingTab' } + }) ) + expect(errorHandler).not.toHaveBeenCalled() renderWithSelectedTarget().unmount() @@ -4356,6 +4362,79 @@ describe('AgentPanelRoot lifecycle', () => { ) }) + it('resets the canvas sync gate when an earlier teardown step throws', () => { + const errorHandler = vi.fn() + vi.mocked(attachDocOpMinter).mockImplementationOnce((deps) => { + docOpMinterDeps.current = deps + return fromPartial({ + detach: vi.fn(() => { + throw new Error('detach failed') + }) + }) + }) + const panel = render(AgentPanelRoot, { + global: { plugins: [i18n], config: { errorHandler } } + }) + const setCanvasSyncGate = vi.spyOn( + useAgentConversationStore(), + 'setCanvasSyncGate' + ) + // Cleared so the only recorded call is the teardown reset, not this + // instance's own live gate registered while it was mounted. + setCanvasSyncGate.mockClear() + + panel.unmount() + + // PM-1575: the gate is reset to the always-safe default even though a + // step three places ahead of it threw. + expect(setCanvasSyncGate).toHaveBeenCalledOnce() + const [gate, outcomeCount] = setCanvasSyncGate.mock.lastCall ?? [] + expect(gate?.()).toBe(false) + expect(outcomeCount?.()).toBe(0) + expect(reportError).toHaveBeenCalledWith( + expect.objectContaining({ message: 'detach failed' }), + expect.objectContaining({ + errorType: 'failure_tearing_down_agent_panel', + tags: { step: 'detachDocOpMinter' } + }) + ) + expect(errorHandler).not.toHaveBeenCalled() + }) + + it('resets the canvas sync gate when reporting a failed teardown step throws', () => { + const errorHandler = vi.fn() + vi.mocked(attachDocOpMinter).mockImplementationOnce((deps) => { + docOpMinterDeps.current = deps + return fromPartial({ + detach: vi.fn(() => { + throw new Error('detach failed') + }) + }) + }) + const panel = render(AgentPanelRoot, { + global: { plugins: [i18n], config: { errorHandler } } + }) + const setCanvasSyncGate = vi.spyOn( + useAgentConversationStore(), + 'setCanvasSyncGate' + ) + setCanvasSyncGate.mockClear() + // The reporter is the one part of the loop outside its own try/catch; a + // telemetry sink torn down ahead of the panel must not take the remaining + // releases with it. + vi.mocked(reportError).mockImplementationOnce(() => { + throw new Error('reporter failed') + }) + + panel.unmount() + + expect(setCanvasSyncGate).toHaveBeenCalledOnce() + const [gate, outcomeCount] = setCanvasSyncGate.mock.lastCall ?? [] + expect(gate?.()).toBe(false) + expect(outcomeCount?.()).toBe(0) + expect(errorHandler).not.toHaveBeenCalled() + }) + it('does not claim the minimap graph-activity layer when setup throws', () => { vi.mocked(useFreeUsePlacement).mockImplementationOnce(() => { throw new Error('setup failed') diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index ef8bdccdabd..46310f3dd0e 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -438,7 +438,43 @@ onMounted(() => { agentMinimapLayer = registerMinimapDecorationLayer('agent.graph-activity') syncAgentMinimapLayer(graphActivity.state) }) -onBeforeUnmount(() => agentMinimapLayer?.dispose()) +// Teardown must be total. Nothing is re-thrown: an error escaping an unmount +// hook reaches Vue's logError, which re-throws outside production builds (this +// app registers no app.config.errorHandler) and aborts both the steps after it +// and the rest of unmountComponent -- stranding this panel's later releases on +// singletons that outlive it, such as the PM-1575 canvas-sync gate below. +// +// Steps are keyed rather than positional for two reasons: the key names the +// failure in telemetry, which is now the only signal that a release was +// skipped, and insertion order is the run order (no key is integer-like, so +// Object.entries order is specified). They return `undefined` rather than +// `void` so an async step -- whose rejection would escape the catch below +// while still looking contained -- fails to compile instead. +function runPanelTeardown( + steps: Readonly undefined>> +): void { + for (const [step, release] of Object.entries(steps)) { + try { + release() + } catch (error) { + try { + reportError(error, { + errorType: 'failure_tearing_down_agent_panel', + tags: { step } + }) + } catch { + // A reporter that throws must not abort the teardown it reports on. + } + } + } +} +onBeforeUnmount(() => + runPanelTeardown({ + disposeMinimapLayer: () => { + agentMinimapLayer?.dispose() + } + }) +) const { accepted: consentAccepted } = storeToRefs(useAgentConsentStore()) const { withConsent } = useAgentConsent() const workspaceStore = useTeamWorkspaceStore() @@ -1187,28 +1223,50 @@ async function onAnswerAsk( void refreshCloudWorkflowIds() onBeforeUnmount(() => { - ++activeTabGeneration - releaseCoachCompletionWaiters() - if ( - (coachDeferredBy.value === null || !agentPanelStore.isVisible) && - composerStore.submission?.id === consentHeldSubmissionId - ) - composerStore.invalidateSubmission() - docOpMinter.detach() - restoreOpMinter.detach() - exitNodeSelectionMode() - stop() - tabActivity.setEditing(null) - tabActivity.setCreating(false) - // PM-1575: the store singleton outlives this component. Without resetting - // the gate here, a remount's own setCanvasSyncGate() call is the only - // thing standing between the old (now torn-down) follower's gate and a - // turn resumed in the meantime reading it -- reset to the always-safe - // default instead of leaving whatever this instance last set. - conversationStore.setCanvasSyncGate( - () => false, - () => 0 - ) + runPanelTeardown({ + invalidateActiveTabGeneration: () => { + ++activeTabGeneration + }, + releaseCoachCompletionWaiters: () => { + releaseCoachCompletionWaiters() + }, + invalidateConsentHeldSubmission: () => { + if ( + (coachDeferredBy.value === null || !agentPanelStore.isVisible) && + composerStore.submission?.id === consentHeldSubmissionId + ) + composerStore.invalidateSubmission() + }, + detachDocOpMinter: () => { + docOpMinter.detach() + }, + detachRestoreOpMinter: () => { + restoreOpMinter.detach() + }, + exitNodeSelectionMode: () => { + exitNodeSelectionMode() + }, + stopSession: () => { + stop() + }, + clearEditingTab: () => { + tabActivity.setEditing(null) + }, + clearCreatingTab: () => { + tabActivity.setCreating(false) + }, + // PM-1575: the store singleton outlives this component. Without resetting + // the gate here, a remount's own setCanvasSyncGate() call is the only + // thing standing between the old (now torn-down) follower's gate and a + // turn resumed in the meantime reading it -- reset to the always-safe + // default instead of leaving whatever this instance last set. + resetCanvasSyncGate: () => { + conversationStore.setCanvasSyncGate( + () => false, + () => 0 + ) + } + }) }) const { copy } = useClipboard({ legacy: true }) @@ -1583,7 +1641,13 @@ const attachment = useAttachment({ remove: composerStore.removeAttachment }) -onBeforeUnmount(() => attachment.cancelAllUploads()) +onBeforeUnmount(() => + runPanelTeardown({ + cancelAllUploads: () => { + attachment.cancelAllUploads() + } + }) +) function onAttach(): void { exitNodeSelectionMode()