mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-04 15:14:10 +00:00
feat(agent): support aborting agent execution in local and temporal modes
This commit is contained in:
@@ -21,6 +21,14 @@ import {
|
|||||||
import * as piAgent from '../index'
|
import * as piAgent from '../index'
|
||||||
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
|
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
|
||||||
import { type DatabaseSessionMetadata } from '../database-session-storage'
|
import { type DatabaseSessionMetadata } from '../database-session-storage'
|
||||||
|
import {
|
||||||
|
isTemporal,
|
||||||
|
triggerLocalCancel,
|
||||||
|
} from '@shumai/workflow-core'
|
||||||
|
import { Context } from '@temporalio/activity'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
prisma,
|
prisma,
|
||||||
AssetType,
|
AssetType,
|
||||||
@@ -46,6 +54,9 @@ vi.mock('../index', async () => {
|
|||||||
describe('Agent Activities', () => {
|
describe('Agent Activities', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
|
vi.spyOn(Context, 'current').mockImplementation(() => {
|
||||||
|
throw new Error('Not in Temporal')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should call agentChatActivity and prompt the harness', async () => {
|
it('should call agentChatActivity and prompt the harness', async () => {
|
||||||
@@ -89,6 +100,127 @@ describe('Agent Activities', () => {
|
|||||||
expect(piAgent.createAgentSession).toHaveBeenCalled()
|
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 () => {
|
it('should include error message in text when stopReason is error', async () => {
|
||||||
const mockHarness = {
|
const mockHarness = {
|
||||||
prompt: vi.fn().mockResolvedValue({
|
prompt: vi.fn().mockResolvedValue({
|
||||||
|
|||||||
@@ -13,7 +13,12 @@ import { s3Service } from '@shumai/core/src/s3/s3'
|
|||||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||||
import { VersionStackService } from '@shumai/core/src/versionStack/versionStack'
|
import { VersionStackService } from '@shumai/core/src/versionStack/versionStack'
|
||||||
import { AssetType, prisma, Prisma, type Skill } from '@shumai/db'
|
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 { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||||
import { ulid } from 'ulid'
|
import { ulid } from 'ulid'
|
||||||
import { DatabaseSessionStorage } from '../database-session-storage'
|
import { DatabaseSessionStorage } from '../database-session-storage'
|
||||||
@@ -53,6 +58,7 @@ export interface AgentExecutionContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function executeAgentPrompt(params: {
|
async function executeAgentPrompt(params: {
|
||||||
|
taskId?: string
|
||||||
teamId: string
|
teamId: string
|
||||||
agentId: string
|
agentId: string
|
||||||
prompt: 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 {
|
try {
|
||||||
if (params.agentsInstruction && params.agentsInstruction.trim()) {
|
if (params.agentsInstruction && params.agentsInstruction.trim()) {
|
||||||
const storage = session.getStorage()
|
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 }
|
return { text, usage, sessionId }
|
||||||
} finally {
|
} finally {
|
||||||
// Cleanup handled by agent session if needed
|
if (heartbeatInterval) {
|
||||||
|
clearInterval(heartbeatInterval)
|
||||||
|
}
|
||||||
|
if (params.taskId) {
|
||||||
|
unregisterLocalCancelHandler(params.taskId)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AgentChatParams {
|
export interface AgentChatParams {
|
||||||
|
taskId?: string
|
||||||
teamId: string
|
teamId: string
|
||||||
agentId: string
|
agentId: string
|
||||||
message: string
|
message: string
|
||||||
@@ -248,6 +293,7 @@ export async function agentChatActivity(params: AgentChatParams) {
|
|||||||
const sessionId = params.sessionId
|
const sessionId = params.sessionId
|
||||||
|
|
||||||
return executeAgentPrompt({
|
return executeAgentPrompt({
|
||||||
|
taskId: params.taskId,
|
||||||
teamId: params.teamId,
|
teamId: params.teamId,
|
||||||
agentId: params.agentId,
|
agentId: params.agentId,
|
||||||
prompt: cleanMessage,
|
prompt: cleanMessage,
|
||||||
|
|||||||
@@ -491,23 +491,25 @@ describe('Agent Chat Workflow', () => {
|
|||||||
])
|
])
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith({
|
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||||
teamId: 't1',
|
expect.objectContaining({
|
||||||
agentId: 'b1',
|
teamId: 't1',
|
||||||
message: 'chatbot prompt',
|
agentId: 'b1',
|
||||||
imageUrls: [],
|
message: 'chatbot prompt',
|
||||||
projectId: 'p1',
|
imageUrls: [],
|
||||||
folderId: '',
|
projectId: 'p1',
|
||||||
agentsInstruction: expectedInstruction,
|
folderId: '',
|
||||||
sessionId: 'session-direct-123',
|
agentsInstruction: expectedInstruction,
|
||||||
userId: undefined,
|
sessionId: 'session-direct-123',
|
||||||
userCommentId: undefined,
|
userId: undefined,
|
||||||
explicitMention: true,
|
userCommentId: undefined,
|
||||||
context: { agent: { id: 'b1' } },
|
explicitMention: true,
|
||||||
attachedAssets: [
|
context: { agent: { id: 'b1' } },
|
||||||
{ id: 'file-attachment-1', name: 'attachment.png', type: 'file' },
|
attachedAssets: [
|
||||||
{ id: 'referenced-asset-1', name: 'ref-folder', type: 'folder' },
|
{ id: 'file-attachment-1', name: 'attachment.png', type: 'file' },
|
||||||
],
|
{ id: 'referenced-asset-1', name: 'ref-folder', type: 'folder' },
|
||||||
})
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -179,6 +179,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
|
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
|
||||||
|
taskId: task.id,
|
||||||
teamId,
|
teamId,
|
||||||
agentId: agentId,
|
agentId: agentId,
|
||||||
message: prompt,
|
message: prompt,
|
||||||
@@ -241,10 +242,25 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
// Update placeholder comment with error message
|
// Update placeholder comment with error message
|
||||||
if (placeholderCommentId && agentWorkerQueue) {
|
if (placeholderCommentId && agentWorkerQueue) {
|
||||||
try {
|
try {
|
||||||
const errorMessage =
|
let errorMessage = 'Sorry, I encountered an error while processing your request.'
|
||||||
err instanceof Error && err.message.startsWith('AI error:')
|
if (err instanceof Error) {
|
||||||
? `AI error: ${err.message.substring(9)}`
|
if (err.message.startsWith('AI error:')) {
|
||||||
: 'Sorry, I encountered an error while processing your request.'
|
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, {
|
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||||
commentId: placeholderCommentId,
|
commentId: placeholderCommentId,
|
||||||
|
|||||||
@@ -4,6 +4,12 @@ import chatRoute from './chat'
|
|||||||
import { chatService } from '@shumai/core/src/chat/chat'
|
import { chatService } from '@shumai/core/src/chat/chat'
|
||||||
import { authzService } from '@shumai/core/src/authz/authz'
|
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) => {
|
vi.mock('@shumai/core/src/chat/chat', async (importOriginal) => {
|
||||||
const original = await importOriginal<typeof import('@shumai/core/src/chat/chat')>()
|
const original = await importOriginal<typeof import('@shumai/core/src/chat/chat')>()
|
||||||
return {
|
return {
|
||||||
@@ -24,11 +30,13 @@ vi.mock('@shumai/db', () => ({
|
|||||||
},
|
},
|
||||||
workflowTask: {
|
workflowTask: {
|
||||||
findUnique: vi.fn(),
|
findUnique: vi.fn(),
|
||||||
|
findMany: vi.fn(),
|
||||||
|
update: vi.fn(),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}))
|
}))
|
||||||
|
|
||||||
import { prisma } from '@shumai/db'
|
import { prisma, type WorkflowTask } from '@shumai/db'
|
||||||
|
|
||||||
describe('Chat API', () => {
|
describe('Chat API', () => {
|
||||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||||
@@ -196,4 +204,54 @@ describe('Chat API', () => {
|
|||||||
expect(text).toContain('{"type":"ping"}')
|
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')
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { chatService, mapEntryToMessage } from '@shumai/core/src/chat/chat'
|
|||||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||||
import { chatRequestSchema, paginationParamsSchema } from '@shumai/dtos'
|
import { chatRequestSchema, paginationParamsSchema } from '@shumai/dtos'
|
||||||
import type { Prisma } from '@shumai/db'
|
import type { Prisma } from '@shumai/db'
|
||||||
|
import { workflowService } from '@shumai/workflow-core'
|
||||||
|
|
||||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
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
|
export default route
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import {
|
|||||||
History,
|
History,
|
||||||
Loader2,
|
Loader2,
|
||||||
Plus,
|
Plus,
|
||||||
|
Square,
|
||||||
Trash2,
|
Trash2,
|
||||||
Wrench,
|
Wrench,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
@@ -50,6 +51,7 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
|
|||||||
deleteSession,
|
deleteSession,
|
||||||
startNewSession,
|
startNewSession,
|
||||||
sendMessage,
|
sendMessage,
|
||||||
|
abortActiveSession,
|
||||||
selectedAgentId,
|
selectedAgentId,
|
||||||
setSelectedAgentId,
|
setSelectedAgentId,
|
||||||
} = useChatbotStore()
|
} = useChatbotStore()
|
||||||
@@ -637,18 +639,32 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
{isStreaming ? (
|
||||||
onClick={handleSend}
|
<button
|
||||||
disabled={isStreaming || !inputText.trim() || !selectedAgentId}
|
onClick={() => {
|
||||||
className={cn(
|
if (teamId) {
|
||||||
'p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm',
|
abortActiveSession(teamId)
|
||||||
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',
|
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"
|
||||||
>
|
>
|
||||||
<ArrowUp className="h-4 w-4" />
|
<Square className="h-4 w-4" />
|
||||||
</button>
|
</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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ interface ChatbotState {
|
|||||||
projectId: string,
|
projectId: string,
|
||||||
contextAssetId?: string,
|
contextAssetId?: string,
|
||||||
) => Promise<void>
|
) => Promise<void>
|
||||||
|
abortActiveSession: (teamId: string) => Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useChatbotStore = create<ChatbotState>((set) => ({
|
export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||||
@@ -303,4 +304,23 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
|||||||
set({ isStreaming: false })
|
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)
|
||||||
|
}
|
||||||
|
},
|
||||||
}))
|
}))
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { WorkflowTask } from '@shumai/db'
|
|||||||
|
|
||||||
export interface Executor {
|
export interface Executor {
|
||||||
submit(task: WorkflowTask): Promise<string>
|
submit(task: WorkflowTask): Promise<string>
|
||||||
|
cancel?(taskId: string): Promise<void>
|
||||||
start(): void
|
start(): void
|
||||||
close(): void
|
close(): void
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -403,4 +403,21 @@ describe('LocalExecutor Integration Tests', () => {
|
|||||||
expect(executor2.getAgentConcurrencyLimit()).toBe(5)
|
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)
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
|||||||
import { Executor } from './executor'
|
import { Executor } from './executor'
|
||||||
import * as taskActivities from './activities/task'
|
import * as taskActivities from './activities/task'
|
||||||
import { logger } from '@shumai/core/src/logger'
|
import { logger } from '@shumai/core/src/logger'
|
||||||
import { getConcurrencyLimit } from './workflow-utils'
|
import { getConcurrencyLimit, triggerLocalCancel } from './workflow-utils'
|
||||||
|
|
||||||
type WorkflowFn = (task: WorkflowTask) => Promise<void>
|
type WorkflowFn = (task: WorkflowTask) => Promise<void>
|
||||||
|
|
||||||
@@ -165,6 +165,10 @@ export class LocalExecutor implements Executor {
|
|||||||
return task.id
|
return task.id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async cancel(taskId: string): Promise<void> {
|
||||||
|
triggerLocalCancel(taskId)
|
||||||
|
}
|
||||||
|
|
||||||
start(): void {
|
start(): void {
|
||||||
if (this.interval) return
|
if (this.interval) return
|
||||||
this.interval = setInterval(() => this.tick(), 5000)
|
this.interval = setInterval(() => this.tick(), 5000)
|
||||||
|
|||||||
@@ -50,6 +50,13 @@ export class TemporalExecutor implements Executor {
|
|||||||
return handle.workflowId
|
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 {
|
start(): void {
|
||||||
// Client doesn't need explicit start
|
// Client doesn't need explicit start
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -203,3 +203,27 @@ export function getConcurrencyLimit(envVar: string | undefined, defaultValue: nu
|
|||||||
}
|
}
|
||||||
return parsed
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -23,6 +23,12 @@ export class WorkflowService {
|
|||||||
return this.executor.submit(task)
|
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> {
|
async executeWait(task: WorkflowTask, timeoutMs: number = 30000): Promise<WorkflowTask> {
|
||||||
const start = Date.now()
|
const start = Date.now()
|
||||||
while (Date.now() - start < timeoutMs) {
|
while (Date.now() - start < timeoutMs) {
|
||||||
|
|||||||
+1
-1
@@ -12,7 +12,7 @@ export default defineConfig({
|
|||||||
exclude: [...configDefaults.exclude, 'packages/webui/e2e/**', 'apps/web/e2e/**'],
|
exclude: [...configDefaults.exclude, 'packages/webui/e2e/**', 'apps/web/e2e/**'],
|
||||||
server: {
|
server: {
|
||||||
deps: {
|
deps: {
|
||||||
inline: ['zod'],
|
inline: ['zod', '@shumai/workflow-core', '@temporalio/activity'],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user