mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 04:57:12 +00:00
Merge pull request #186 from shumaiOne/feat/agent-abort
feat(agent): support aborting agent execution
This commit is contained in:
@@ -305,6 +305,7 @@ We use `prisma-json-types-generator` to enforce strict type-safety for Prisma `J
|
||||
|
||||
- Development: Use `bun --bun run prisma migrate dev` to create and apply migrations during development.
|
||||
- Production: Use `bun --bun run prisma migrate deploy` to apply pending migrations in production environments.
|
||||
- **No Automatic Dev DB Reset**: Do not run `prisma migrate reset --force` or commands that force-reset the database automatically. If migrations become out of sync or a reset is required, stop executing, report the situation to the user, and present suggested manual cleanup/reset steps for the user to execute.
|
||||
|
||||
### Commands
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ 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 { triggerLocalCancel } from '@shumai/workflow-core'
|
||||
import { Context } from '@temporalio/activity'
|
||||
|
||||
import {
|
||||
prisma,
|
||||
AssetType,
|
||||
@@ -46,6 +49,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 +95,140 @@ 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!: (value: {
|
||||
content: Array<{ type: string; text: string } | { type: string }>
|
||||
usage: { input: number; output: number }
|
||||
stopReason?: string
|
||||
errorMessage?: string
|
||||
}) => void
|
||||
const promptPromise = new Promise<Parameters<typeof resolvePrompt>[0]>((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!: (value: {
|
||||
content: Array<{ type: string; text: string } | { type: string }>
|
||||
usage: { input: number; output: number }
|
||||
stopReason?: string
|
||||
errorMessage?: string
|
||||
}) => void
|
||||
const promptPromise = new Promise<Parameters<typeof resolvePrompt>[0]>((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 removeEventListenerSpy = vi.spyOn(mockTemporalContext.cancellationSignal, 'removeEventListener')
|
||||
|
||||
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
|
||||
expect(removeEventListenerSpy).toHaveBeenCalledWith('abort', expect.any(Function))
|
||||
addEventListenerSpy.mockRestore()
|
||||
removeEventListenerSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should include error message in text when stopReason is error', async () => {
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
|
||||
@@ -13,7 +13,8 @@ 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 { registerLocalCancelHandler, unregisterLocalCancelHandler } from '@shumai/workflow-core'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { ulid } from 'ulid'
|
||||
import { DatabaseSessionStorage } from '../database-session-storage'
|
||||
@@ -53,6 +54,7 @@ export interface AgentExecutionContext {
|
||||
}
|
||||
|
||||
async function executeAgentPrompt(params: {
|
||||
taskId?: string
|
||||
teamId: string
|
||||
agentId: string
|
||||
prompt: string
|
||||
@@ -149,6 +151,35 @@ If you need to create files in the local filesystem (for example, a temporary fi
|
||||
}
|
||||
}
|
||||
|
||||
let heartbeatInterval: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const onAbort = () => {
|
||||
harness.abort()
|
||||
}
|
||||
|
||||
let temporalSignal: EventTarget | undefined
|
||||
try {
|
||||
temporalSignal = Context.current().cancellationSignal
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
if (temporalSignal) {
|
||||
temporalSignal.addEventListener('abort', onAbort, { 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 +254,20 @@ 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 (temporalSignal) {
|
||||
temporalSignal.removeEventListener('abort', onAbort)
|
||||
}
|
||||
if (params.taskId) {
|
||||
unregisterLocalCancelHandler(params.taskId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface AgentChatParams {
|
||||
taskId?: string
|
||||
teamId: string
|
||||
agentId: string
|
||||
message: string
|
||||
@@ -248,6 +288,7 @@ export async function agentChatActivity(params: AgentChatParams) {
|
||||
const sessionId = params.sessionId
|
||||
|
||||
return executeAgentPrompt({
|
||||
taskId: params.taskId,
|
||||
teamId: params.teamId,
|
||||
agentId: params.agentId,
|
||||
prompt: cleanMessage,
|
||||
|
||||
@@ -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' },
|
||||
],
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(),
|
||||
findFirst: 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,55 @@ 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 mockActiveTask = {
|
||||
id: 'task1',
|
||||
status: 'processing',
|
||||
type: 'chat',
|
||||
sessionId: 'session1',
|
||||
payload: {
|
||||
agent: {
|
||||
sessionId: 'session1',
|
||||
},
|
||||
},
|
||||
}
|
||||
vi.mocked(prisma.workflowTask.findFirst).mockResolvedValue(
|
||||
mockActiveTask 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.findFirst).mockResolvedValue(null)
|
||||
|
||||
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 { 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,41 @@ 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 taskToAbort = await prisma.workflowTask.findFirst({
|
||||
where: {
|
||||
status: { in: ['pending', 'processing'] },
|
||||
type: 'chat',
|
||||
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
|
||||
|
||||
@@ -292,6 +292,7 @@ export class ChatService {
|
||||
status: 'pending',
|
||||
teamId,
|
||||
projectId,
|
||||
sessionId: activeSessionId,
|
||||
payload: {
|
||||
projectId,
|
||||
agent: {
|
||||
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "workflow_tasks" ADD COLUMN "session_id" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "workflow_tasks_session_id_idx" ON "workflow_tasks"("session_id");
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
-- Backfill session_id from existing task payloads
|
||||
UPDATE "workflow_tasks"
|
||||
SET "session_id" = (payload->'agent'->>'sessionId')
|
||||
WHERE "session_id" IS NULL AND (payload->'agent'->>'sessionId') IS NOT NULL;
|
||||
@@ -629,6 +629,7 @@ model WorkflowTask {
|
||||
inputTokens Int @default(0) @map("input_tokens")
|
||||
outputTokens Int @default(0) @map("output_tokens")
|
||||
model String?
|
||||
sessionId String? @map("session_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@ -638,6 +639,7 @@ model WorkflowTask {
|
||||
@@index([teamId])
|
||||
@@index([projectId])
|
||||
@@index([type])
|
||||
@@index([sessionId])
|
||||
}
|
||||
enum AgentType {
|
||||
chat
|
||||
|
||||
+3
-3
File diff suppressed because one or more lines are too long
@@ -3266,6 +3266,7 @@ export const WorkflowTaskScalarFieldEnum = {
|
||||
inputTokens: 'inputTokens',
|
||||
outputTokens: 'outputTokens',
|
||||
model: 'model',
|
||||
sessionId: 'sessionId',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
} as const
|
||||
|
||||
@@ -451,6 +451,7 @@ export const WorkflowTaskScalarFieldEnum = {
|
||||
inputTokens: 'inputTokens',
|
||||
outputTokens: 'outputTokens',
|
||||
model: 'model',
|
||||
sessionId: 'sessionId',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
} as const
|
||||
|
||||
+29
-1
@@ -50,6 +50,7 @@ export type WorkflowTaskMinAggregateOutputType = {
|
||||
inputTokens: number | null
|
||||
outputTokens: number | null
|
||||
model: string | null
|
||||
sessionId: string | null
|
||||
createdAt: Date | null
|
||||
updatedAt: Date | null
|
||||
}
|
||||
@@ -66,6 +67,7 @@ export type WorkflowTaskMaxAggregateOutputType = {
|
||||
inputTokens: number | null
|
||||
outputTokens: number | null
|
||||
model: string | null
|
||||
sessionId: string | null
|
||||
createdAt: Date | null
|
||||
updatedAt: Date | null
|
||||
}
|
||||
@@ -84,6 +86,7 @@ export type WorkflowTaskCountAggregateOutputType = {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
model: number
|
||||
sessionId: number
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
_all: number
|
||||
@@ -112,6 +115,7 @@ export type WorkflowTaskMinAggregateInputType = {
|
||||
inputTokens?: true
|
||||
outputTokens?: true
|
||||
model?: true
|
||||
sessionId?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
}
|
||||
@@ -128,6 +132,7 @@ export type WorkflowTaskMaxAggregateInputType = {
|
||||
inputTokens?: true
|
||||
outputTokens?: true
|
||||
model?: true
|
||||
sessionId?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
}
|
||||
@@ -146,6 +151,7 @@ export type WorkflowTaskCountAggregateInputType = {
|
||||
inputTokens?: true
|
||||
outputTokens?: true
|
||||
model?: true
|
||||
sessionId?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
_all?: true
|
||||
@@ -251,6 +257,7 @@ export type WorkflowTaskGroupByOutputType = {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
model: string | null
|
||||
sessionId: string | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
_count: WorkflowTaskCountAggregateOutputType | null
|
||||
@@ -292,6 +299,7 @@ export type WorkflowTaskWhereInput = {
|
||||
inputTokens?: Prisma.IntFilter<"WorkflowTask"> | number
|
||||
outputTokens?: Prisma.IntFilter<"WorkflowTask"> | number
|
||||
model?: Prisma.StringNullableFilter<"WorkflowTask"> | string | null
|
||||
sessionId?: Prisma.StringNullableFilter<"WorkflowTask"> | string | null
|
||||
createdAt?: Prisma.DateTimeFilter<"WorkflowTask"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<"WorkflowTask"> | Date | string
|
||||
}
|
||||
@@ -310,6 +318,7 @@ export type WorkflowTaskOrderByWithRelationInput = {
|
||||
inputTokens?: Prisma.SortOrder
|
||||
outputTokens?: Prisma.SortOrder
|
||||
model?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
sessionId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
}
|
||||
@@ -331,6 +340,7 @@ export type WorkflowTaskWhereUniqueInput = Prisma.AtLeast<{
|
||||
inputTokens?: Prisma.IntFilter<"WorkflowTask"> | number
|
||||
outputTokens?: Prisma.IntFilter<"WorkflowTask"> | number
|
||||
model?: Prisma.StringNullableFilter<"WorkflowTask"> | string | null
|
||||
sessionId?: Prisma.StringNullableFilter<"WorkflowTask"> | string | null
|
||||
createdAt?: Prisma.DateTimeFilter<"WorkflowTask"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<"WorkflowTask"> | Date | string
|
||||
}, "id">
|
||||
@@ -349,6 +359,7 @@ export type WorkflowTaskOrderByWithAggregationInput = {
|
||||
inputTokens?: Prisma.SortOrder
|
||||
outputTokens?: Prisma.SortOrder
|
||||
model?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
sessionId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
_count?: Prisma.WorkflowTaskCountOrderByAggregateInput
|
||||
@@ -375,6 +386,7 @@ export type WorkflowTaskScalarWhereWithAggregatesInput = {
|
||||
inputTokens?: Prisma.IntWithAggregatesFilter<"WorkflowTask"> | number
|
||||
outputTokens?: Prisma.IntWithAggregatesFilter<"WorkflowTask"> | number
|
||||
model?: Prisma.StringNullableWithAggregatesFilter<"WorkflowTask"> | string | null
|
||||
sessionId?: Prisma.StringNullableWithAggregatesFilter<"WorkflowTask"> | string | null
|
||||
createdAt?: Prisma.DateTimeWithAggregatesFilter<"WorkflowTask"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"WorkflowTask"> | Date | string
|
||||
}
|
||||
@@ -393,6 +405,7 @@ export type WorkflowTaskCreateInput = {
|
||||
inputTokens?: number
|
||||
outputTokens?: number
|
||||
model?: string | null
|
||||
sessionId?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
}
|
||||
@@ -411,6 +424,7 @@ export type WorkflowTaskUncheckedCreateInput = {
|
||||
inputTokens?: number
|
||||
outputTokens?: number
|
||||
model?: string | null
|
||||
sessionId?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
}
|
||||
@@ -429,6 +443,7 @@ export type WorkflowTaskUpdateInput = {
|
||||
inputTokens?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
outputTokens?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
model?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
sessionId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
}
|
||||
@@ -447,6 +462,7 @@ export type WorkflowTaskUncheckedUpdateInput = {
|
||||
inputTokens?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
outputTokens?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
model?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
sessionId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
}
|
||||
@@ -465,6 +481,7 @@ export type WorkflowTaskCreateManyInput = {
|
||||
inputTokens?: number
|
||||
outputTokens?: number
|
||||
model?: string | null
|
||||
sessionId?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
}
|
||||
@@ -483,6 +500,7 @@ export type WorkflowTaskUpdateManyMutationInput = {
|
||||
inputTokens?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
outputTokens?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
model?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
sessionId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
}
|
||||
@@ -501,6 +519,7 @@ export type WorkflowTaskUncheckedUpdateManyInput = {
|
||||
inputTokens?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
outputTokens?: Prisma.IntFieldUpdateOperationsInput | number
|
||||
model?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
sessionId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
}
|
||||
@@ -519,6 +538,7 @@ export type WorkflowTaskCountOrderByAggregateInput = {
|
||||
inputTokens?: Prisma.SortOrder
|
||||
outputTokens?: Prisma.SortOrder
|
||||
model?: Prisma.SortOrder
|
||||
sessionId?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
}
|
||||
@@ -540,6 +560,7 @@ export type WorkflowTaskMaxOrderByAggregateInput = {
|
||||
inputTokens?: Prisma.SortOrder
|
||||
outputTokens?: Prisma.SortOrder
|
||||
model?: Prisma.SortOrder
|
||||
sessionId?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
}
|
||||
@@ -556,6 +577,7 @@ export type WorkflowTaskMinOrderByAggregateInput = {
|
||||
inputTokens?: Prisma.SortOrder
|
||||
outputTokens?: Prisma.SortOrder
|
||||
model?: Prisma.SortOrder
|
||||
sessionId?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
}
|
||||
@@ -589,6 +611,7 @@ export type WorkflowTaskSelect<ExtArgs extends runtime.Types.Extensions.Internal
|
||||
inputTokens?: boolean
|
||||
outputTokens?: boolean
|
||||
model?: boolean
|
||||
sessionId?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
}, ExtArgs["result"]["workflowTask"]>
|
||||
@@ -607,6 +630,7 @@ export type WorkflowTaskSelectCreateManyAndReturn<ExtArgs extends runtime.Types.
|
||||
inputTokens?: boolean
|
||||
outputTokens?: boolean
|
||||
model?: boolean
|
||||
sessionId?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
}, ExtArgs["result"]["workflowTask"]>
|
||||
@@ -625,6 +649,7 @@ export type WorkflowTaskSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.
|
||||
inputTokens?: boolean
|
||||
outputTokens?: boolean
|
||||
model?: boolean
|
||||
sessionId?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
}, ExtArgs["result"]["workflowTask"]>
|
||||
@@ -643,11 +668,12 @@ export type WorkflowTaskSelectScalar = {
|
||||
inputTokens?: boolean
|
||||
outputTokens?: boolean
|
||||
model?: boolean
|
||||
sessionId?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
}
|
||||
|
||||
export type WorkflowTaskOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "uid" | "teamId" | "projectId" | "assetId" | "type" | "status" | "payload" | "output" | "heartbeat" | "inputTokens" | "outputTokens" | "model" | "createdAt" | "updatedAt", ExtArgs["result"]["workflowTask"]>
|
||||
export type WorkflowTaskOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "uid" | "teamId" | "projectId" | "assetId" | "type" | "status" | "payload" | "output" | "heartbeat" | "inputTokens" | "outputTokens" | "model" | "sessionId" | "createdAt" | "updatedAt", ExtArgs["result"]["workflowTask"]>
|
||||
|
||||
export type $WorkflowTaskPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
name: "WorkflowTask"
|
||||
@@ -672,6 +698,7 @@ export type $WorkflowTaskPayload<ExtArgs extends runtime.Types.Extensions.Intern
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
model: string | null
|
||||
sessionId: string | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}, ExtArgs["result"]["workflowTask"]>
|
||||
@@ -1110,6 +1137,7 @@ export interface WorkflowTaskFieldRefs {
|
||||
readonly inputTokens: Prisma.FieldRef<"WorkflowTask", 'Int'>
|
||||
readonly outputTokens: Prisma.FieldRef<"WorkflowTask", 'Int'>
|
||||
readonly model: Prisma.FieldRef<"WorkflowTask", 'String'>
|
||||
readonly sessionId: Prisma.FieldRef<"WorkflowTask", 'String'>
|
||||
readonly createdAt: Prisma.FieldRef<"WorkflowTask", 'DateTime'>
|
||||
readonly updatedAt: Prisma.FieldRef<"WorkflowTask", 'DateTime'>
|
||||
}
|
||||
|
||||
@@ -75,6 +75,7 @@ describe('Transcode Workflow', () => {
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
@@ -166,6 +167,7 @@ describe('Transcode Workflow', () => {
|
||||
assetId: 'asset-image',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
@@ -249,6 +251,7 @@ describe('Transcode Workflow', () => {
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
@@ -281,6 +284,7 @@ describe('Transcode Workflow', () => {
|
||||
assetId: 'asset-video',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
@@ -344,6 +348,7 @@ describe('Transcode Workflow', () => {
|
||||
assetId: 'asset-image',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
@@ -396,6 +401,7 @@ describe('Transcode Workflow', () => {
|
||||
assetId: 'asset-audio',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
@@ -15,16 +15,16 @@ import { useDroppable } from '@dnd-kit/react'
|
||||
import type { ChatMessage } from '@shumai/dtos'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import {
|
||||
ArrowLeft,
|
||||
ArrowUp,
|
||||
Bot,
|
||||
Brain,
|
||||
ChevronDown,
|
||||
History,
|
||||
Loader2,
|
||||
Plus,
|
||||
Trash2,
|
||||
Wrench,
|
||||
ArrowLeft,
|
||||
ArrowUp,
|
||||
Bot,
|
||||
Brain,
|
||||
ChevronDown,
|
||||
History,
|
||||
Loader2,
|
||||
Plus,
|
||||
Trash2,
|
||||
Wrench,
|
||||
} from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import Markdown from 'react-markdown'
|
||||
@@ -50,6 +50,7 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
|
||||
deleteSession,
|
||||
startNewSession,
|
||||
sendMessage,
|
||||
abortActiveSession,
|
||||
selectedAgentId,
|
||||
setSelectedAgentId,
|
||||
} = useChatbotStore()
|
||||
@@ -629,26 +630,39 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
|
||||
</Select>
|
||||
) : (
|
||||
<div className="flex items-center gap-1.5 px-2 py-1 text-[11px] text-muted-foreground/60 italic select-none">
|
||||
<Bot className="h-3.5 w-3.5" />
|
||||
<span>
|
||||
{m.no_chat_agents_warning ? m.no_chat_agents_warning() : 'No agents'}
|
||||
</span>
|
||||
<span>{m.no_chat_agents_warning()}</span>
|
||||
</div>
|
||||
)}
|
||||
</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"
|
||||
>
|
||||
<div className="h-4 w-4 flex items-center justify-center">
|
||||
<div className="h-3 w-3 bg-current rounded-[2px] bg-white" />
|
||||
</div>
|
||||
</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>
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
@@ -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'],
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user