From 636e92af4c27f393d806128705003e277921876c Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 14 Jul 2026 16:08:43 +0800 Subject: [PATCH] fix(agent): unregister temporal cancellation listener on completion --- packages/agent/src/activities/agent.test.ts | 3 +++ packages/agent/src/activities/agent.ts | 15 ++++++++------- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index 75bae7ed..0fa3d2cf 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -195,6 +195,7 @@ describe('Agent Activities', () => { } as unknown as AgentExecutionContext const addEventListenerSpy = vi.spyOn(mockTemporalContext.cancellationSignal, 'addEventListener') + const removeEventListenerSpy = vi.spyOn(mockTemporalContext.cancellationSignal, 'removeEventListener') const executionPromise = agentChatActivity({ teamId: 't1', @@ -223,7 +224,9 @@ describe('Agent Activities', () => { }) await executionPromise + expect(removeEventListenerSpy).toHaveBeenCalledWith('abort', expect.any(Function)) addEventListenerSpy.mockRestore() + removeEventListenerSpy.mockRestore() }) it('should include error message in text when stopReason is error', async () => { diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index 2327f3b5..d952b597 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -153,6 +153,10 @@ If you need to create files in the local filesystem (for example, a temporary fi let heartbeatInterval: ReturnType | null = null + const onAbort = () => { + harness.abort() + } + let temporalSignal: EventTarget | undefined try { temporalSignal = Context.current().cancellationSignal @@ -161,13 +165,7 @@ If you need to create files in the local filesystem (for example, a temporary fi } if (temporalSignal) { - temporalSignal.addEventListener( - 'abort', - () => { - harness.abort() - }, - { once: true }, - ) + temporalSignal.addEventListener('abort', onAbort, { once: true }) heartbeatInterval = setInterval(() => { try { @@ -259,6 +257,9 @@ If you need to create files in the local filesystem (for example, a temporary fi if (heartbeatInterval) { clearInterval(heartbeatInterval) } + if (temporalSignal) { + temporalSignal.removeEventListener('abort', onAbort) + } if (params.taskId) { unregisterLocalCancelHandler(params.taskId) }