From 8a942d4f4e0ad1410cf9436bfce6508f05066c09 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 14 Jul 2026 10:25:06 +0800 Subject: [PATCH] feat(agent): support aborting agent execution in local and temporal modes --- packages/agent/src/activities/agent.test.ts | 132 ++++++++++++++++++ packages/agent/src/activities/agent.ts | 50 ++++++- .../agent/src/workflows/agent-chat.test.ts | 38 ++--- packages/agent/src/workflows/agent-chat.ts | 24 +++- packages/api/src/chat.test.ts | 60 +++++++- packages/api/src/chat.ts | 40 ++++++ packages/webui/components/chatbot-sidebar.tsx | 40 ++++-- packages/webui/stores/chatbot.ts | 20 +++ packages/workflow-core/src/executor.ts | 1 + .../workflow-core/src/local-executor.test.ts | 17 +++ packages/workflow-core/src/local-executor.ts | 6 +- .../workflow-core/src/temporal-executor.ts | 7 + packages/workflow-core/src/workflow-utils.ts | 24 ++++ packages/workflow-core/src/workflow.ts | 6 + vitest.config.ts | 2 +- 15 files changed, 428 insertions(+), 39 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index c36d395f..fed655bb 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -21,6 +21,14 @@ import { import * as piAgent from '../index' import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core' import { type DatabaseSessionMetadata } from '../database-session-storage' +import { + isTemporal, + triggerLocalCancel, +} from '@shumai/workflow-core' +import { Context } from '@temporalio/activity' + + + import { prisma, AssetType, @@ -46,6 +54,9 @@ vi.mock('../index', async () => { describe('Agent Activities', () => { beforeEach(() => { vi.clearAllMocks() + vi.spyOn(Context, 'current').mockImplementation(() => { + throw new Error('Not in Temporal') + }) }) it('should call agentChatActivity and prompt the harness', async () => { @@ -89,6 +100,127 @@ describe('Agent Activities', () => { expect(piAgent.createAgentSession).toHaveBeenCalled() }) + it('should register local cancellation handler and call harness.abort when cancelled in local mode', async () => { + let resolvePrompt: any + const promptPromise = new Promise((resolve) => { + resolvePrompt = resolve + }) + + const mockHarness = { + prompt: vi.fn().mockReturnValue(promptPromise), + abort: vi.fn(), + } + const mockSession = { + getEntries: vi.fn().mockResolvedValue([]), + getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), + } + + vi.mocked(piAgent.createAgentSession).mockResolvedValue({ + session: mockSession as unknown as Session, + harness: mockHarness as unknown as AgentHarness, + }) + + const context = { + agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, + dbProviders: [], + teamSkills: [], + allowedDomains: [], + } as unknown as AgentExecutionContext + + const executionPromise = agentChatActivity({ + taskId: 'task-123', + teamId: 't1', + agentId: 'b1', + message: 'Hi', + imageUrls: [], + projectId: 'p1', + folderId: 'f1', + sessionId: 'mock-session-id', + context, + }) + + // Yield to let the asynchronous setup register the cancel handler + await new Promise((resolve) => setTimeout(resolve, 50)) + + // Simulate user cancellation + const cancelled = triggerLocalCancel('task-123') + expect(cancelled).toBe(true) + expect(mockHarness.abort).toHaveBeenCalled() + + // Resolve the prompt promise to allow the activity to finish clean + resolvePrompt({ + content: [{ type: 'text', text: 'AI response' }], + usage: { input: 10, output: 20 }, + }) + + await executionPromise + }) + + it('should listen to Temporal cancellation signal and call harness.abort when cancelled in Temporal mode', async () => { + const mockTemporalContext = { + cancellationSignal: new EventTarget(), + heartbeat: vi.fn(), + } as unknown as Context + vi.spyOn(Context, 'current').mockReturnValue(mockTemporalContext) + + let resolvePrompt: any + const promptPromise = new Promise((resolve) => { + resolvePrompt = resolve + }) + + const mockHarness = { + prompt: vi.fn().mockReturnValue(promptPromise), + abort: vi.fn(), + } + const mockSession = { + getEntries: vi.fn().mockResolvedValue([]), + getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), + } + + vi.mocked(piAgent.createAgentSession).mockResolvedValue({ + session: mockSession as unknown as Session, + harness: mockHarness as unknown as AgentHarness, + }) + + const context = { + agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, + dbProviders: [], + teamSkills: [], + allowedDomains: [], + } as unknown as AgentExecutionContext + + const addEventListenerSpy = vi.spyOn(mockTemporalContext.cancellationSignal, 'addEventListener') + + const executionPromise = agentChatActivity({ + teamId: 't1', + agentId: 'b1', + message: 'Hi', + imageUrls: [], + projectId: 'p1', + folderId: 'f1', + sessionId: 'mock-session-id', + context, + }) + + // Yield to let the asynchronous setup add the abort event listener + await new Promise((resolve) => setTimeout(resolve, 50)) + + expect(addEventListenerSpy).toHaveBeenCalledWith('abort', expect.any(Function), { once: true }) + + // Simulate Temporal cancellation event + mockTemporalContext.cancellationSignal.dispatchEvent(new Event('abort')) + expect(mockHarness.abort).toHaveBeenCalled() + + // Resolve the prompt promise to allow the activity to finish clean + resolvePrompt({ + content: [{ type: 'text', text: 'AI response' }], + usage: { input: 10, output: 20 }, + }) + + await executionPromise + addEventListenerSpy.mockRestore() + }) + it('should include error message in text when stopReason is error', async () => { const mockHarness = { prompt: vi.fn().mockResolvedValue({ diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index 4215c723..20b1448f 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -13,7 +13,12 @@ import { s3Service } from '@shumai/core/src/s3/s3' import { uploadService } from '@shumai/core/src/upload/upload' import { VersionStackService } from '@shumai/core/src/versionStack/versionStack' import { AssetType, prisma, Prisma, type Skill } from '@shumai/db' -import { ApplicationFailure } from '@temporalio/activity' +import { ApplicationFailure, Context } from '@temporalio/activity' +import { + isTemporal, + registerLocalCancelHandler, + unregisterLocalCancelHandler, +} from '@shumai/workflow-core' import { generateKeyBetween } from 'jittered-fractional-indexing' import { ulid } from 'ulid' import { DatabaseSessionStorage } from '../database-session-storage' @@ -53,6 +58,7 @@ export interface AgentExecutionContext { } async function executeAgentPrompt(params: { + taskId?: string teamId: string agentId: string prompt: string @@ -149,6 +155,39 @@ If you need to create files in the local filesystem (for example, a temporary fi } } + let heartbeatInterval: ReturnType | null = null + + let isTemporalActivity = false + let temporalSignal: any + try { + temporalSignal = Context.current().cancellationSignal + isTemporalActivity = true + } catch { + isTemporalActivity = false + } + + if (isTemporalActivity && temporalSignal) { + temporalSignal.addEventListener( + 'abort', + () => { + harness.abort() + }, + { once: true }, + ) + + heartbeatInterval = setInterval(() => { + try { + Context.current().heartbeat() + } catch (err) { + logger.debug({ err }, 'Failed to send activity heartbeat') + } + }, 2000) + } else if (params.taskId) { + registerLocalCancelHandler(params.taskId, () => { + harness.abort() + }) + } + try { if (params.agentsInstruction && params.agentsInstruction.trim()) { const storage = session.getStorage() @@ -223,11 +262,17 @@ If you need to create files in the local filesystem (for example, a temporary fi } return { text, usage, sessionId } } finally { - // Cleanup handled by agent session if needed + if (heartbeatInterval) { + clearInterval(heartbeatInterval) + } + if (params.taskId) { + unregisterLocalCancelHandler(params.taskId) + } } } export interface AgentChatParams { + taskId?: string teamId: string agentId: string message: string @@ -248,6 +293,7 @@ export async function agentChatActivity(params: AgentChatParams) { const sessionId = params.sessionId return executeAgentPrompt({ + taskId: params.taskId, teamId: params.teamId, agentId: params.agentId, prompt: cleanMessage, diff --git a/packages/agent/src/workflows/agent-chat.test.ts b/packages/agent/src/workflows/agent-chat.test.ts index 1bf86efb..d5d05ea8 100644 --- a/packages/agent/src/workflows/agent-chat.test.ts +++ b/packages/agent/src/workflows/agent-chat.test.ts @@ -491,23 +491,25 @@ describe('Agent Chat Workflow', () => { ]) .build() - expect(mockActivities.agentChatActivity).toHaveBeenCalledWith({ - teamId: 't1', - agentId: 'b1', - message: 'chatbot prompt', - imageUrls: [], - projectId: 'p1', - folderId: '', - agentsInstruction: expectedInstruction, - sessionId: 'session-direct-123', - userId: undefined, - userCommentId: undefined, - explicitMention: true, - context: { agent: { id: 'b1' } }, - attachedAssets: [ - { id: 'file-attachment-1', name: 'attachment.png', type: 'file' }, - { id: 'referenced-asset-1', name: 'ref-folder', type: 'folder' }, - ], - }) + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( + expect.objectContaining({ + teamId: 't1', + agentId: 'b1', + message: 'chatbot prompt', + imageUrls: [], + projectId: 'p1', + folderId: '', + agentsInstruction: expectedInstruction, + sessionId: 'session-direct-123', + userId: undefined, + userCommentId: undefined, + explicitMention: true, + context: { agent: { id: 'b1' } }, + attachedAssets: [ + { id: 'file-attachment-1', name: 'attachment.png', type: 'file' }, + { id: 'referenced-asset-1', name: 'ref-folder', type: 'folder' }, + ], + }), + ) }) }) diff --git a/packages/agent/src/workflows/agent-chat.ts b/packages/agent/src/workflows/agent-chat.ts index d6330db9..fb8e65c9 100644 --- a/packages/agent/src/workflows/agent-chat.ts +++ b/packages/agent/src/workflows/agent-chat.ts @@ -179,6 +179,7 @@ export async function agentChat(task: WorkflowTask): Promise { } const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, { + taskId: task.id, teamId, agentId: agentId, message: prompt, @@ -241,10 +242,25 @@ export async function agentChat(task: WorkflowTask): Promise { // Update placeholder comment with error message if (placeholderCommentId && agentWorkerQueue) { try { - const errorMessage = - err instanceof Error && err.message.startsWith('AI error:') - ? `AI error: ${err.message.substring(9)}` - : 'Sorry, I encountered an error while processing your request.' + let errorMessage = 'Sorry, I encountered an error while processing your request.' + if (err instanceof Error) { + if (err.message.startsWith('AI error:')) { + errorMessage = `AI error: ${err.message.substring(9)}` + } else if ( + err.message.includes('aborted') || + err.message.includes('abort') || + err.name === 'AbortError' || + err.message.includes('cancel') + ) { + errorMessage = 'Agent execution stopped.' + } + } else if ( + String(err).includes('aborted') || + String(err).includes('abort') || + String(err).includes('cancel') + ) { + errorMessage = 'Agent execution stopped.' + } await executeActivity(agentWorkerQueue, updateCommentActivity, { commentId: placeholderCommentId, diff --git a/packages/api/src/chat.test.ts b/packages/api/src/chat.test.ts index fb6d24be..0f62f3ba 100644 --- a/packages/api/src/chat.test.ts +++ b/packages/api/src/chat.test.ts @@ -4,6 +4,12 @@ import chatRoute from './chat' import { chatService } from '@shumai/core/src/chat/chat' import { authzService } from '@shumai/core/src/authz/authz' +vi.mock('@shumai/workflow-core', () => ({ + workflowService: { + cancel: vi.fn(), + }, +})) + vi.mock('@shumai/core/src/chat/chat', async (importOriginal) => { const original = await importOriginal() return { @@ -24,11 +30,13 @@ vi.mock('@shumai/db', () => ({ }, workflowTask: { findUnique: vi.fn(), + findMany: vi.fn(), + update: vi.fn(), }, }, })) -import { prisma } from '@shumai/db' +import { prisma, type WorkflowTask } from '@shumai/db' describe('Chat API', () => { const app = new Hono<{ Variables: { user: { id: string; name: string } } }>() @@ -196,4 +204,54 @@ describe('Chat API', () => { expect(text).toContain('{"type":"ping"}') }) }) + + describe('POST /teams/:teamId/chat/sessions/:sessionId/abort', () => { + it('aborts an active chat session and updates task status', async () => { + const mockActiveTasks = [ + { + id: 'task1', + status: 'processing', + type: 'chat', + payload: { + agent: { + sessionId: 'session1', + }, + }, + }, + ] + vi.mocked(prisma.workflowTask.findMany).mockResolvedValue(mockActiveTasks as unknown as WorkflowTask[]) + vi.mocked(prisma.workflowTask.update).mockResolvedValue({} as unknown as WorkflowTask) + + const { workflowService } = await import('@shumai/workflow-core') + + const res = await app.request('/teams/team1/chat/sessions/session1/abort', { + method: 'POST', + }) + + expect(res.status).toBe(200) + const data = await res.json() + expect(data).toEqual({ success: true }) + + expect(workflowService.cancel).toHaveBeenCalledWith('task1') + expect(prisma.workflowTask.update).toHaveBeenCalledWith({ + where: { id: 'task1' }, + data: { + status: 'failed', + output: { error: 'aborted' }, + }, + }) + }) + + it('returns 404 if no active task is found for the session', async () => { + vi.mocked(prisma.workflowTask.findMany).mockResolvedValue([]) + + const res = await app.request('/teams/team1/chat/sessions/session1/abort', { + method: 'POST', + }) + + expect(res.status).toBe(404) + const data = await res.json() + expect(data.error).toBe('No active execution found for this session') + }) + }) }) diff --git a/packages/api/src/chat.ts b/packages/api/src/chat.ts index ac13aaf2..002f52b9 100644 --- a/packages/api/src/chat.ts +++ b/packages/api/src/chat.ts @@ -6,6 +6,7 @@ import { chatService, mapEntryToMessage } from '@shumai/core/src/chat/chat' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { chatRequestSchema, paginationParamsSchema } from '@shumai/dtos' import type { Prisma } from '@shumai/db' +import { workflowService } from '@shumai/workflow-core' type User = Prisma.UserGetPayload> @@ -173,5 +174,44 @@ const route = new Hono<{ Variables: { user: User } }>() } }) }) + .post('/teams/:teamId/chat/sessions/:sessionId/abort', async (c) => { + const user = c.get('user') + const teamId = c.req.param('teamId') + const sessionId = c.req.param('sessionId') + + await authzService.hasPermission({ + user, + permission: Permission.Read, + type: ResourceType.Team, + id: teamId, + }) + + const activeTasks = await prisma.workflowTask.findMany({ + where: { + status: { in: ['pending', 'processing'] }, + type: 'chat', + }, + }) + + const taskToAbort = activeTasks.find( + (t) => (t.payload as PrismaJson.WorkflowTaskPayload)?.agent?.sessionId === sessionId, + ) + + if (!taskToAbort) { + return c.json({ error: 'No active execution found for this session' }, 404) + } + + await workflowService.cancel(taskToAbort.id) + + await prisma.workflowTask.update({ + where: { id: taskToAbort.id }, + data: { + status: 'failed', + output: { error: 'aborted' }, + }, + }) + + return c.json({ success: true }, 200) + }) export default route diff --git a/packages/webui/components/chatbot-sidebar.tsx b/packages/webui/components/chatbot-sidebar.tsx index 2a1560fe..4225aa4d 100644 --- a/packages/webui/components/chatbot-sidebar.tsx +++ b/packages/webui/components/chatbot-sidebar.tsx @@ -23,6 +23,7 @@ import { History, Loader2, Plus, + Square, Trash2, Wrench, } from 'lucide-react' @@ -50,6 +51,7 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp deleteSession, startNewSession, sendMessage, + abortActiveSession, selectedAgentId, setSelectedAgentId, } = useChatbotStore() @@ -637,18 +639,32 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp )} - + {isStreaming ? ( + + ) : ( + + )} diff --git a/packages/webui/stores/chatbot.ts b/packages/webui/stores/chatbot.ts index 5fef4fb9..12815c83 100644 --- a/packages/webui/stores/chatbot.ts +++ b/packages/webui/stores/chatbot.ts @@ -43,6 +43,7 @@ interface ChatbotState { projectId: string, contextAssetId?: string, ) => Promise + abortActiveSession: (teamId: string) => Promise } export const useChatbotStore = create((set) => ({ @@ -303,4 +304,23 @@ export const useChatbotStore = create((set) => ({ set({ isStreaming: false }) } }, + + abortActiveSession: async (teamId) => { + const { currentSessionId, isStreaming } = useChatbotStore.getState() + if (!currentSessionId || !isStreaming) return + + try { + const res = await client.api.teams[':teamId'].chat.sessions[':sessionId'].abort.$post({ + param: { teamId, sessionId: currentSessionId }, + }) + if (res.ok) { + toast.success('Agent execution stopped') + } else { + throw new Error('Failed to abort agent execution') + } + } catch (err) { + const errMsg = err instanceof Error ? err.message : 'Failed to abort execution' + toast.error(errMsg) + } + }, })) diff --git a/packages/workflow-core/src/executor.ts b/packages/workflow-core/src/executor.ts index 865bbebc..4ee80b3a 100644 --- a/packages/workflow-core/src/executor.ts +++ b/packages/workflow-core/src/executor.ts @@ -2,6 +2,7 @@ import { WorkflowTask } from '@shumai/db' export interface Executor { submit(task: WorkflowTask): Promise + cancel?(taskId: string): Promise start(): void close(): void } diff --git a/packages/workflow-core/src/local-executor.test.ts b/packages/workflow-core/src/local-executor.test.ts index 1b7388ca..1acacc19 100644 --- a/packages/workflow-core/src/local-executor.test.ts +++ b/packages/workflow-core/src/local-executor.test.ts @@ -403,4 +403,21 @@ describe('LocalExecutor Integration Tests', () => { expect(executor2.getAgentConcurrencyLimit()).toBe(5) }) }) + + describe('Cancellation', () => { + it('registers and triggers local cancel handlers', async () => { + const { registerLocalCancelHandler, unregisterLocalCancelHandler } = + await import('./workflow-utils') + + const cancelSpy = vi.fn() + const taskId = 'task-cancel-test' + + registerLocalCancelHandler(taskId, cancelSpy) + + await executor.cancel(taskId) + expect(cancelSpy).toHaveBeenCalled() + + unregisterLocalCancelHandler(taskId) + }) + }) }) diff --git a/packages/workflow-core/src/local-executor.ts b/packages/workflow-core/src/local-executor.ts index fa50e72f..1ca671bc 100644 --- a/packages/workflow-core/src/local-executor.ts +++ b/packages/workflow-core/src/local-executor.ts @@ -3,7 +3,7 @@ import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db' import { Executor } from './executor' import * as taskActivities from './activities/task' import { logger } from '@shumai/core/src/logger' -import { getConcurrencyLimit } from './workflow-utils' +import { getConcurrencyLimit, triggerLocalCancel } from './workflow-utils' type WorkflowFn = (task: WorkflowTask) => Promise @@ -165,6 +165,10 @@ export class LocalExecutor implements Executor { return task.id } + async cancel(taskId: string): Promise { + triggerLocalCancel(taskId) + } + start(): void { if (this.interval) return this.interval = setInterval(() => this.tick(), 5000) diff --git a/packages/workflow-core/src/temporal-executor.ts b/packages/workflow-core/src/temporal-executor.ts index b2ae8ecc..1e2144ef 100644 --- a/packages/workflow-core/src/temporal-executor.ts +++ b/packages/workflow-core/src/temporal-executor.ts @@ -50,6 +50,13 @@ export class TemporalExecutor implements Executor { return handle.workflowId } + async cancel(taskId: string): Promise { + const client = await this.getClient() + const workflowId = `chat-${taskId}` + const handle = client.workflow.getHandle(workflowId) + await handle.cancel() + } + start(): void { // Client doesn't need explicit start } diff --git a/packages/workflow-core/src/workflow-utils.ts b/packages/workflow-core/src/workflow-utils.ts index 1dc4b6ec..ce374483 100644 --- a/packages/workflow-core/src/workflow-utils.ts +++ b/packages/workflow-core/src/workflow-utils.ts @@ -203,3 +203,27 @@ export function getConcurrencyLimit(envVar: string | undefined, defaultValue: nu } return parsed } + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const globalObjWithCancel = globalThis as any +if (!globalObjWithCancel.__localCancelHandlers) { + globalObjWithCancel.__localCancelHandlers = new Map void>() +} +const localCancelHandlers: Map void> = globalObjWithCancel.__localCancelHandlers + +export function registerLocalCancelHandler(taskId: string, cancelFn: () => void) { + localCancelHandlers.set(taskId, cancelFn) +} + +export function unregisterLocalCancelHandler(taskId: string) { + localCancelHandlers.delete(taskId) +} + +export function triggerLocalCancel(taskId: string): boolean { + const handler = localCancelHandlers.get(taskId) + if (handler) { + handler() + return true + } + return false +} diff --git a/packages/workflow-core/src/workflow.ts b/packages/workflow-core/src/workflow.ts index d92ac343..94655db6 100644 --- a/packages/workflow-core/src/workflow.ts +++ b/packages/workflow-core/src/workflow.ts @@ -23,6 +23,12 @@ export class WorkflowService { return this.executor.submit(task) } + async cancel(taskId: string): Promise { + if (this.executor.cancel) { + await this.executor.cancel(taskId) + } + } + async executeWait(task: WorkflowTask, timeoutMs: number = 30000): Promise { const start = Date.now() while (Date.now() - start < timeoutMs) { diff --git a/vitest.config.ts b/vitest.config.ts index 03923092..f5664142 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -12,7 +12,7 @@ export default defineConfig({ exclude: [...configDefaults.exclude, 'packages/webui/e2e/**', 'apps/web/e2e/**'], server: { deps: { - inline: ['zod'], + inline: ['zod', '@shumai/workflow-core', '@temporalio/activity'], }, }, },