feat(agent): support aborting agent execution in local and temporal modes

This commit is contained in:
yiling
2026-07-14 10:25:06 +08:00
parent e772581542
commit 8a942d4f4e
15 changed files with 428 additions and 39 deletions
+132
View File
@@ -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<DatabaseSessionMetadata>,
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<DatabaseSessionMetadata>,
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({
+48 -2
View File
@@ -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<typeof setInterval> | 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,
+20 -18
View File
@@ -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' },
],
}),
)
})
})
+20 -4
View File
@@ -179,6 +179,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
}
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<void> {
// 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,
+59 -1
View File
@@ -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<typeof import('@shumai/core/src/chat/chat')>()
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')
})
})
})
+40
View File
@@ -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<Record<string, never>>
@@ -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
+28 -12
View File
@@ -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
)}
</div>
<button
onClick={handleSend}
disabled={isStreaming || !inputText.trim() || !selectedAgentId}
className={cn(
'p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm',
inputText.trim() && !isStreaming && selectedAgentId
? 'bg-primary text-primary-foreground hover:bg-primary/95 transform hover:-translate-y-0.5'
: 'bg-muted text-muted-foreground cursor-not-allowed opacity-50',
)}
>
<ArrowUp className="h-4 w-4" />
</button>
{isStreaming ? (
<button
onClick={() => {
if (teamId) {
abortActiveSession(teamId)
}
}}
className="p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm bg-destructive text-destructive-foreground hover:bg-destructive/90 transform hover:-translate-y-0.5"
title="Stop generation"
>
<Square className="h-4 w-4" />
</button>
) : (
<button
onClick={handleSend}
disabled={!inputText.trim() || !selectedAgentId}
className={cn(
'p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm',
inputText.trim() && selectedAgentId
? 'bg-primary text-primary-foreground hover:bg-primary/95 transform hover:-translate-y-0.5'
: 'bg-muted text-muted-foreground cursor-not-allowed opacity-50',
)}
>
<ArrowUp className="h-4 w-4" />
</button>
)}
</div>
</div>
</div>
+20
View File
@@ -43,6 +43,7 @@ interface ChatbotState {
projectId: string,
contextAssetId?: string,
) => Promise<void>
abortActiveSession: (teamId: string) => Promise<void>
}
export const useChatbotStore = create<ChatbotState>((set) => ({
@@ -303,4 +304,23 @@ export const useChatbotStore = create<ChatbotState>((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)
}
},
}))
+1
View File
@@ -2,6 +2,7 @@ import { WorkflowTask } from '@shumai/db'
export interface Executor {
submit(task: WorkflowTask): Promise<string>
cancel?(taskId: string): Promise<void>
start(): void
close(): void
}
@@ -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)
})
})
})
+5 -1
View File
@@ -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<void>
@@ -165,6 +165,10 @@ export class LocalExecutor implements Executor {
return task.id
}
async cancel(taskId: string): Promise<void> {
triggerLocalCancel(taskId)
}
start(): void {
if (this.interval) return
this.interval = setInterval(() => this.tick(), 5000)
@@ -50,6 +50,13 @@ export class TemporalExecutor implements Executor {
return handle.workflowId
}
async cancel(taskId: string): Promise<void> {
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
}
@@ -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<string, () => void>()
}
const localCancelHandlers: Map<string, () => 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
}
+6
View File
@@ -23,6 +23,12 @@ export class WorkflowService {
return this.executor.submit(task)
}
async cancel(taskId: string): Promise<void> {
if (this.executor.cancel) {
await this.executor.cancel(taskId)
}
}
async executeWait(task: WorkflowTask, timeoutMs: number = 30000): Promise<WorkflowTask> {
const start = Date.now()
while (Date.now() - start < timeoutMs) {
+1 -1
View File
@@ -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'],
},
},
},