From b018fd0fec452eb7e6769b5ffc90f31c00414214 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 15 Jul 2026 10:14:59 +0800 Subject: [PATCH 1/6] feat(workflow-e2e): add E2E tests for agentAutofillMedia workflow - Setup E2E package under packages/e2e - Use testcontainers to spin up postgres and temporal dev server - Overwrite activities in global registry to mock AI model output - Track temporal workers and expose shutdownWorkers() method for clean shutdown - Integrate test:e2e:workflow into root package.json and GitHub actions CI --- .github/workflows/ci.yaml | 23 ++ bun.lock | 40 +++- package.json | 1 + packages/e2e/package.json | 14 ++ packages/e2e/tsconfig.json | 7 + packages/e2e/vitest.config.ts | 17 ++ packages/e2e/workflow/agent-autofill.test.ts | 237 +++++++++++++++++++ packages/e2e/workflow/test-global-setup.ts | 49 ++++ packages/workflow-core/src/workflow.ts | 10 + tsconfig.json | 3 +- 10 files changed, 387 insertions(+), 14 deletions(-) create mode 100644 packages/e2e/package.json create mode 100644 packages/e2e/tsconfig.json create mode 100644 packages/e2e/vitest.config.ts create mode 100644 packages/e2e/workflow/agent-autofill.test.ts create mode 100644 packages/e2e/workflow/test-global-setup.ts diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index eaed76c5..01adc6c8 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -138,3 +138,26 @@ jobs: name: playwright-report-app-${{ matrix.project }} path: playwright-report/ retention-days: 7 + + workflow_e2e: + name: Workflow E2E + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Bun + uses: oven-sh/setup-bun@v1 + with: + bun-version: latest + + - name: Install dependencies + run: bun install + + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y ripgrep bubblewrap socat ffmpeg + + - name: Run Workflow E2E Tests + run: bun run test:e2e:workflow diff --git a/bun.lock b/bun.lock index 9fe0e9b9..ed8b1892 100644 --- a/bun.lock +++ b/bun.lock @@ -37,7 +37,7 @@ }, "apps/agent": { "name": "@shumai/agent-app", - "version": "0.1.8", + "version": "0.1.9", "bin": { "shumai-agent": "./src/index.ts", }, @@ -49,7 +49,7 @@ }, "apps/cli": { "name": "@shumai/cli", - "version": "0.1.8", + "version": "0.1.9", "bin": { "shumai-cli": "./src/index.ts", }, @@ -64,7 +64,7 @@ }, "apps/transcode": { "name": "@shumai/transcode-app", - "version": "0.1.8", + "version": "0.1.9", "bin": { "shumai-transcode": "./src/index.ts", }, @@ -76,7 +76,7 @@ }, "apps/web": { "name": "@shumai/web-app", - "version": "0.1.8", + "version": "0.1.9", "dependencies": { "@shumai/agent": "workspace:*", "@shumai/api": "workspace:*", @@ -96,7 +96,7 @@ }, "packages/agent": { "name": "@shumai/agent", - "version": "0.1.8", + "version": "0.1.9", "dependencies": { "@anthropic-ai/sandbox-runtime": "0.0.52", "@earendil-works/pi-agent-core": "0.78.0", @@ -120,7 +120,7 @@ }, "packages/api": { "name": "@shumai/api", - "version": "0.1.8", + "version": "0.1.9", "dependencies": { "@hono/zod-validator": "0.7.6", "@shumai/core": "workspace:*", @@ -134,7 +134,7 @@ }, "packages/core": { "name": "@shumai/core", - "version": "0.1.8", + "version": "0.1.9", "dependencies": { "@earendil-works/pi-agent-core": "0.78.0", "@shumai/db": "workspace:*", @@ -162,7 +162,7 @@ }, "packages/db": { "name": "@shumai/db", - "version": "0.1.8", + "version": "0.1.9", "dependencies": { "@earendil-works/pi-agent-core": "0.78.0", "@prisma/adapter-pg": "7.8.0", @@ -178,19 +178,31 @@ }, "packages/dtos": { "name": "@shumai/dtos", - "version": "0.1.8", + "version": "0.1.9", "dependencies": { "@earendil-works/pi-agent-core": "0.78.0", "zod": "4.4.3", }, }, + "packages/e2e": { + "name": "@shumai/e2e", + "version": "0.1.9", + "dependencies": { + "@shumai/agent": "workspace:*", + "@shumai/core": "workspace:*", + "@shumai/db": "workspace:*", + "@shumai/dtos": "workspace:*", + "@shumai/transcode": "workspace:*", + "@shumai/workflow-core": "workspace:*", + }, + }, "packages/tableprinter": { "name": "@shumai/tableprinter", - "version": "0.1.8", + "version": "0.1.9", }, "packages/transcode": { "name": "@shumai/transcode", - "version": "0.1.8", + "version": "0.1.9", "dependencies": { "@shumai/core": "workspace:*", "@shumai/db": "workspace:*", @@ -204,7 +216,7 @@ }, "packages/webui": { "name": "@shumai/webui", - "version": "0.1.8", + "version": "0.1.9", "dependencies": { "@base-ui/react": "1.5.0", "@dnd-kit/abstract": "0.4.0", @@ -301,7 +313,7 @@ }, "packages/workflow-core": { "name": "@shumai/workflow-core", - "version": "0.1.8", + "version": "0.1.9", "dependencies": { "@shumai/core": "workspace:*", "@shumai/db": "workspace:*", @@ -1010,6 +1022,8 @@ "@shumai/dtos": ["@shumai/dtos@workspace:packages/dtos"], + "@shumai/e2e": ["@shumai/e2e@workspace:packages/e2e"], + "@shumai/tableprinter": ["@shumai/tableprinter@workspace:packages/tableprinter"], "@shumai/transcode": ["@shumai/transcode@workspace:packages/transcode"], diff --git a/package.json b/package.json index d8099d0d..4a05bc81 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "test": "bun --bun vitest run", "test:e2e": "playwright test", + "test:e2e:workflow": "WORKFLOW_EXECUTOR=local bun --bun vitest run -c packages/e2e/vitest.config.ts && WORKFLOW_EXECUTOR=temporal bun --bun vitest run -c packages/e2e/vitest.config.ts", "test:e2e:ui": "playwright test --ui", "test:e2e:report": "playwright show-report", "test:e2e:install": "playwright install --with-deps", diff --git a/packages/e2e/package.json b/packages/e2e/package.json new file mode 100644 index 00000000..733d0c70 --- /dev/null +++ b/packages/e2e/package.json @@ -0,0 +1,14 @@ +{ + "name": "@shumai/e2e", + "version": "0.1.9", + "private": true, + "type": "module", + "dependencies": { + "@shumai/db": "workspace:*", + "@shumai/core": "workspace:*", + "@shumai/workflow-core": "workspace:*", + "@shumai/agent": "workspace:*", + "@shumai/transcode": "workspace:*", + "@shumai/dtos": "workspace:*" + } +} diff --git a/packages/e2e/tsconfig.json b/packages/e2e/tsconfig.json new file mode 100644 index 00000000..d6425e4b --- /dev/null +++ b/packages/e2e/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "ignoreDeprecations": "6.0" + }, + "include": ["workflow/**/*"] +} diff --git a/packages/e2e/vitest.config.ts b/packages/e2e/vitest.config.ts new file mode 100644 index 00000000..9c4ccd6b --- /dev/null +++ b/packages/e2e/vitest.config.ts @@ -0,0 +1,17 @@ +import tsconfigPaths from 'vite-tsconfig-paths' +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + plugins: [tsconfigPaths()], + test: { + globalSetup: './packages/e2e/workflow/test-global-setup.ts', + globals: false, + pool: 'forks', + include: ['packages/e2e/workflow/**/*.test.ts'], + server: { + deps: { + inline: ['zod', '@shumai/workflow-core', '@temporalio/activity'], + }, + }, + }, +}) diff --git a/packages/e2e/workflow/agent-autofill.test.ts b/packages/e2e/workflow/agent-autofill.test.ts new file mode 100644 index 00000000..056fbe5a --- /dev/null +++ b/packages/e2e/workflow/agent-autofill.test.ts @@ -0,0 +1,237 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest' +import { prisma } from '@shumai/db' +import { setupTestDbHooks } from '@shumai/db/test' +import { workflowService, TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core' +import { initAgentWorkflows } from '@shumai/agent' +import { initTranscodeWorkflows } from '@shumai/transcode' +import { s3Service } from '@shumai/core/src/s3/s3' +import { fileURLToPath } from 'url' +import * as path from 'path' + +const currentDir = path.dirname(fileURLToPath(import.meta.url)) +const agentWorkflowsPath = path.resolve(currentDir, '../../../apps/agent/src/workflows.ts') +const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts') + +// No module mocks needed because we override activities directly in the global registry below + +describe('Workflow E2E - agentAutofillMedia', () => { + setupTestDbHooks() + + let agentWorkerPromise: Promise | null = null + let transcodeWorkerPromise: Promise | null = null + + beforeAll(async () => { + // Set bucket environment + process.env.S3_BUCKET = 'shumai-e2e-test-bucket' + + // Initialize registries + initAgentWorkflows() + initTranscodeWorkflows() + + // Override the AI activity with a mock implementation in the global registry + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const localActs = (globalThis as any).__localActivities + if (localActs) { + localActs.autofillAiActivity = async () => { + return { + text: JSON.stringify({ title: 'E2E Title Extracted' }), + usage: { inputTokens: 10, outputTokens: 20, model: 'gemini' }, + sessionId: 'mock-session-123', + } + } + } + + const type = process.env.WORKFLOW_EXECUTOR || 'local' + if (type === 'temporal') { + console.log('Starting background workers for Temporal E2E tests...') + agentWorkerPromise = workflowService.startWorkers(TaskQueueAgent, { + workflowsPath: agentWorkflowsPath, + }) + transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, { + workflowsPath: transcodeWorkflowsPath, + }) + + // Wait a moment for workers to establish connections + await new Promise((resolve) => setTimeout(resolve, 2000)) + } else { + console.log('Starting local workflow service polling...') + workflowService.start() + } + }) + + afterAll(async () => { + const type = process.env.WORKFLOW_EXECUTOR || 'local' + if (type === 'temporal') { + console.log('Shutting down Temporal workers...') + await workflowService.shutdownWorkers() + await Promise.all([agentWorkerPromise, transcodeWorkerPromise].filter(Boolean)) + } + + workflowService.close() + + // Clean up E2E files in local filesystem storage + try { + console.log('Cleaning up local E2E storage files...') + await s3Service.deletePrefix('shumai-e2e-test-bucket', '') + } catch (err) { + console.error('Failed to clean up E2E storage folder:', err) + } + }) + + it('should run agentAutofillMedia workflow and update asset metadata successfully', async () => { + // 1. Seed Database Models + const team = await prisma.team.create({ + data: { name: 'E2E Test Team' }, + }) + + const project = await prisma.project.create({ + data: { name: 'E2E Test Project', teamId: team.id }, + }) + + // Create Metadata Field (aiAutofill = true) + await prisma.metadataField.create({ + data: { + key: 'title', + scope: 'PROJECT', + projectId: project.id, + teamId: team.id, + config: { name: 'Title', type: 'text' }, + aiAutofill: true, + description: 'Auto-extracted title', + }, + }) + + // Create Agent User + const agentUser = await prisma.user.create({ + data: { + name: 'E2E Autofill Agent User', + email: 'e2e-autofill-agent@shumai.ai', + type: 'agent', + }, + }) + + // Link Agent User to Team + await prisma.teamMember.create({ + data: { + teamId: team.id, + userId: agentUser.id, + role: 'editor', + }, + }) + + // Setup Agent Provider & Model configuration + const provider = await prisma.provider.create({ + data: { + name: 'google', + teamId: team.id, + config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' }, + }, + }) + + const model = await prisma.model.create({ + data: { + modelId: 'gemini', + name: 'Gemini', + providerId: provider.id, + config: { + input: ['text', 'image'], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 8192, + maxTokens: 2048, + reasoning: false, + }, + }, + }) + + const agent = await prisma.agent.create({ + data: { + id: agentUser.id, + teamId: team.id, + type: 'autofill', + enabled: true, + providerId: provider.id, + modelId: model.id, + config: { + provider: 'google', + model: 'gemini', + }, + }, + }) + + // Create StorageKey first + const storageKey = await prisma.storageKey.create({ + data: { + key: 'projects/e2e/test-image.png', + }, + }) + + // Create Asset + const asset = await prisma.asset.create({ + data: { + name: 'test-image.png', + type: 'file', + status: 'uploaded', + mediaType: 'image/png', + projectId: project.id, + storageKeyId: storageKey.id, + }, + }) + + // 2. Seed S3 Storage (LocalStorageService) with a valid 1x1 base64-encoded PNG image + const base64Png = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=' + const pngBuffer = Buffer.from(base64Png, 'base64') + await s3Service.putObject( + 'shumai-e2e-test-bucket', + 'projects/e2e/test-image.png', + pngBuffer, + pngBuffer.length, + 'image/png', + ) + + // 3. Create Workflow Task (ai_metadata_autofill, pending) + const task = await prisma.workflowTask.create({ + data: { + type: 'ai_metadata_autofill', + status: 'pending', + assetId: asset.id, + projectId: project.id, + teamId: team.id, + payload: { + projectId: project.id, + agent: { sessionId: 'mock-session-123', agentId: agent.id }, + }, + }, + }) + + // 4. Wait for workflow to complete + console.log(`Submitted E2E Workflow Task. ID: ${task.id}. Awaiting completion...`) + const completedTask = await workflowService.executeWait(task, 45000) + + // 5. Verification + expect(completedTask.status).toBe('completed') + + // Verify placeholder comment is updated correctly + const comments = await prisma.assetComment.findMany({ + where: { assetId: asset.id }, + orderBy: { createdAt: 'asc' }, + }) + expect(comments.length).toBeGreaterThan(0) + // The last updated message of placeholder comment should indicate success + const finalComment = comments[comments.length - 1] + expect(finalComment.message).toBe('Autofill completed successfully.') + + // Verify AssetMetadataValue contains the AI-extracted title + const metadataValue = await prisma.assetMetadataValue.findUnique({ + where: { + // eslint-disable-next-line @typescript-eslint/naming-convention + assetId_fieldKey: { + assetId: asset.id, + fieldKey: 'title', + }, + }, + }) + expect(metadataValue).toBeDefined() + expect(metadataValue?.stringValue).toBe('E2E Title Extracted') + }, 50000) +}) diff --git a/packages/e2e/workflow/test-global-setup.ts b/packages/e2e/workflow/test-global-setup.ts new file mode 100644 index 00000000..c1c0440a --- /dev/null +++ b/packages/e2e/workflow/test-global-setup.ts @@ -0,0 +1,49 @@ +import { setup as dbSetup, teardown as dbTeardown } from '../../db/src/test-global-setup' +import { GenericContainer, StartedTestContainer } from 'testcontainers' + +let temporalContainer: StartedTestContainer | null = null + +export async function setup() { + // 1. Start Postgres DB container & run migrations + await dbSetup() + + // 2. Start Temporal Dev Server container if running in temporal mode + if (process.env.WORKFLOW_EXECUTOR === 'temporal') { + console.log('Starting Temporal Dev Server container using testcontainers...') + try { + temporalContainer = await new GenericContainer('temporalio/temporal:latest') + .withExposedPorts(7233, 8233) + .withCommand(['server', 'start-dev', '--ip', '0.0.0.0']) + .start() + + const host = temporalContainer.getHost() + const mappedPort = temporalContainer.getMappedPort(7233) + const address = `${host}:${mappedPort}` + + process.env.TEMPORAL_ADDRESS = address + console.log(`Temporal Dev Server container started. Address: ${address}`) + + // Brief sleep to ensure temporal dev server is fully ready to accept gRPC clients + await new Promise((resolve) => setTimeout(resolve, 2000)) + } catch (err) { + console.error('Failed to start Temporal Dev Server container:', err) + throw err + } + } +} + +export async function teardown() { + // 1. Stop Temporal container if running + if (temporalContainer) { + console.log('Stopping Temporal Dev Server container...') + try { + await temporalContainer.stop() + } catch (err) { + console.error('Failed to stop Temporal Dev Server container:', err) + } + temporalContainer = null + } + + // 2. Stop Postgres DB container + await dbTeardown() +} diff --git a/packages/workflow-core/src/workflow.ts b/packages/workflow-core/src/workflow.ts index 94655db6..e80fb644 100644 --- a/packages/workflow-core/src/workflow.ts +++ b/packages/workflow-core/src/workflow.ts @@ -9,6 +9,7 @@ import { TaskQueueAgent, TaskQueueTranscode, getConcurrencyLimit } from './workf export class WorkflowService { private executor: Executor + private activeWorkers: unknown[] = [] constructor() { const type = process.env.WORKFLOW_EXECUTOR || 'local' @@ -64,6 +65,13 @@ export class WorkflowService { this.executor.close() } + async shutdownWorkers(): Promise { + await Promise.all( + this.activeWorkers.map((w) => (w as { shutdown: () => Promise }).shutdown()), + ) + this.activeWorkers = [] + } + // Starts Temporal workers for specific task queues async startWorkers( queue: string, @@ -156,6 +164,8 @@ export class WorkflowService { }, }) + this.activeWorkers.push(sharedWorker, specificWorker) + await Promise.all([sharedWorker.run(), specificWorker.run()]) } else { console.log( diff --git a/tsconfig.json b/tsconfig.json index 5a23a2e0..7af2623d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -26,7 +26,8 @@ "@shumai/transcode": ["./packages/transcode/src/index.ts"], "@shumai/transcode/src/*": ["./packages/transcode/src/*"], "@shumai/cli": ["./apps/cli/src/index.ts"], - "@shumai/tableprinter": ["./packages/tableprinter/src/index.ts"] + "@shumai/tableprinter": ["./packages/tableprinter/src/index.ts"], + "@shumai/e2e/*": ["./packages/e2e/*"] } }, "exclude": ["node_modules"] From 83c427e646bd26161d5484249d4ae07b7e521f2a Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 15 Jul 2026 10:52:01 +0800 Subject: [PATCH 2/6] refactor(e2e): mock LLM prompt via AgentHarness prototype spy instead of global activity override --- bun.lock | 1 + packages/e2e/package.json | 3 +- packages/e2e/workflow/agent-autofill.test.ts | 40 +++++++++++++------- 3 files changed, 29 insertions(+), 15 deletions(-) diff --git a/bun.lock b/bun.lock index ed8b1892..1d06ec5f 100644 --- a/bun.lock +++ b/bun.lock @@ -188,6 +188,7 @@ "name": "@shumai/e2e", "version": "0.1.9", "dependencies": { + "@earendil-works/pi-agent-core": "0.78.0", "@shumai/agent": "workspace:*", "@shumai/core": "workspace:*", "@shumai/db": "workspace:*", diff --git a/packages/e2e/package.json b/packages/e2e/package.json index 733d0c70..104b50c6 100644 --- a/packages/e2e/package.json +++ b/packages/e2e/package.json @@ -9,6 +9,7 @@ "@shumai/workflow-core": "workspace:*", "@shumai/agent": "workspace:*", "@shumai/transcode": "workspace:*", - "@shumai/dtos": "workspace:*" + "@shumai/dtos": "workspace:*", + "@earendil-works/pi-agent-core": "0.78.0" } } diff --git a/packages/e2e/workflow/agent-autofill.test.ts b/packages/e2e/workflow/agent-autofill.test.ts index 056fbe5a..0d6d55cf 100644 --- a/packages/e2e/workflow/agent-autofill.test.ts +++ b/packages/e2e/workflow/agent-autofill.test.ts @@ -1,10 +1,11 @@ -import { describe, it, expect, beforeAll, afterAll } from 'vitest' +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest' import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' import { workflowService, TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core' import { initAgentWorkflows } from '@shumai/agent' import { initTranscodeWorkflows } from '@shumai/transcode' import { s3Service } from '@shumai/core/src/s3/s3' +import { AgentHarness, type AgentTool } from '@earendil-works/pi-agent-core' import { fileURLToPath } from 'url' import * as path from 'path' @@ -12,8 +13,6 @@ const currentDir = path.dirname(fileURLToPath(import.meta.url)) const agentWorkflowsPath = path.resolve(currentDir, '../../../apps/agent/src/workflows.ts') const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts') -// No module mocks needed because we override activities directly in the global registry below - describe('Workflow E2E - agentAutofillMedia', () => { setupTestDbHooks() @@ -28,18 +27,28 @@ describe('Workflow E2E - agentAutofillMedia', () => { initAgentWorkflows() initTranscodeWorkflows() - // Override the AI activity with a mock implementation in the global registry - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const localActs = (globalThis as any).__localActivities - if (localActs) { - localActs.autofillAiActivity = async () => { - return { - text: JSON.stringify({ title: 'E2E Title Extracted' }), - usage: { inputTokens: 10, outputTokens: 20, model: 'gemini' }, - sessionId: 'mock-session-123', - } + // Spy on the harness prompt method to intercept the LLM call while running real activities & tools + vi.spyOn(AgentHarness.prototype, 'prompt').mockImplementation(async function ( + this: AgentHarness, + ) { + // Find the real autofill_metadata tool configured on the harness + const tools = this.getTools() + const autofillTool = tools.find((t: AgentTool) => t.name === 'autofill_metadata') + + if (autofillTool) { + // Execute the real tool callback to perform the actual DB updates + await autofillTool.execute('call-123', { title: 'E2E Title Extracted' }) } - } + + // Return a successful assistant response mock + /* eslint-disable @typescript-eslint/no-explicit-any -- Mock assistant response structure */ + return { + content: [{ type: 'text', text: 'Success' }], + usage: { input: 10, output: 20 }, + stopReason: 'stop', + } as any + /* eslint-enable @typescript-eslint/no-explicit-any */ + }) const type = process.env.WORKFLOW_EXECUTOR || 'local' if (type === 'temporal') { @@ -69,6 +78,9 @@ describe('Workflow E2E - agentAutofillMedia', () => { workflowService.close() + // Restore spied methods + vi.restoreAllMocks() + // Clean up E2E files in local filesystem storage try { console.log('Cleaning up local E2E storage files...') From d524a81ecd6d9fc32e27af092a1f739dce5ee5ca Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 15 Jul 2026 11:40:57 +0800 Subject: [PATCH 3/6] chore(vitest): exclude packages/e2e/** from root unit test suite --- package.json | 2 +- packages/e2e/workflow/agent-autofill.test.ts | 11 +++--- packages/e2e/workflow/test-global-setup.ts | 36 +++++++++---------- .../src/workflow-workers.test.ts | 8 ++--- packages/workflow-core/src/workflow.ts | 10 +++++- vitest.config.ts | 9 +++-- 6 files changed, 41 insertions(+), 35 deletions(-) diff --git a/package.json b/package.json index 4a05bc81..11905fd2 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "test": "bun --bun vitest run", "test:e2e": "playwright test", - "test:e2e:workflow": "WORKFLOW_EXECUTOR=local bun --bun vitest run -c packages/e2e/vitest.config.ts && WORKFLOW_EXECUTOR=temporal bun --bun vitest run -c packages/e2e/vitest.config.ts", + "test:e2e:workflow": "bun --bun vitest run -c packages/e2e/vitest.config.ts", "test:e2e:ui": "playwright test --ui", "test:e2e:report": "playwright show-report", "test:e2e:install": "playwright install --with-deps", diff --git a/packages/e2e/workflow/agent-autofill.test.ts b/packages/e2e/workflow/agent-autofill.test.ts index 0d6d55cf..122d7477 100644 --- a/packages/e2e/workflow/agent-autofill.test.ts +++ b/packages/e2e/workflow/agent-autofill.test.ts @@ -13,7 +13,7 @@ const currentDir = path.dirname(fileURLToPath(import.meta.url)) const agentWorkflowsPath = path.resolve(currentDir, '../../../apps/agent/src/workflows.ts') const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts') -describe('Workflow E2E - agentAutofillMedia', () => { +describe.each(['local', 'temporal'] as const)('Workflow E2E - agentAutofillMedia (executor: %s)', (mode) => { setupTestDbHooks() let agentWorkerPromise: Promise | null = null @@ -23,6 +23,9 @@ describe('Workflow E2E - agentAutofillMedia', () => { // Set bucket environment process.env.S3_BUCKET = 'shumai-e2e-test-bucket' + // Configure the workflow service executor dynamically + workflowService.setExecutorType(mode) + // Initialize registries initAgentWorkflows() initTranscodeWorkflows() @@ -50,8 +53,7 @@ describe('Workflow E2E - agentAutofillMedia', () => { /* eslint-enable @typescript-eslint/no-explicit-any */ }) - const type = process.env.WORKFLOW_EXECUTOR || 'local' - if (type === 'temporal') { + if (mode === 'temporal') { console.log('Starting background workers for Temporal E2E tests...') agentWorkerPromise = workflowService.startWorkers(TaskQueueAgent, { workflowsPath: agentWorkflowsPath, @@ -69,8 +71,7 @@ describe('Workflow E2E - agentAutofillMedia', () => { }) afterAll(async () => { - const type = process.env.WORKFLOW_EXECUTOR || 'local' - if (type === 'temporal') { + if (mode === 'temporal') { console.log('Shutting down Temporal workers...') await workflowService.shutdownWorkers() await Promise.all([agentWorkerPromise, transcodeWorkerPromise].filter(Boolean)) diff --git a/packages/e2e/workflow/test-global-setup.ts b/packages/e2e/workflow/test-global-setup.ts index c1c0440a..ca6c41ec 100644 --- a/packages/e2e/workflow/test-global-setup.ts +++ b/packages/e2e/workflow/test-global-setup.ts @@ -7,28 +7,26 @@ export async function setup() { // 1. Start Postgres DB container & run migrations await dbSetup() - // 2. Start Temporal Dev Server container if running in temporal mode - if (process.env.WORKFLOW_EXECUTOR === 'temporal') { - console.log('Starting Temporal Dev Server container using testcontainers...') - try { - temporalContainer = await new GenericContainer('temporalio/temporal:latest') - .withExposedPorts(7233, 8233) - .withCommand(['server', 'start-dev', '--ip', '0.0.0.0']) - .start() + // 2. Start Temporal Dev Server container for the test suite + console.log('Starting Temporal Dev Server container using testcontainers...') + try { + temporalContainer = await new GenericContainer('temporalio/temporal:latest') + .withExposedPorts(7233, 8233) + .withCommand(['server', 'start-dev', '--ip', '0.0.0.0']) + .start() - const host = temporalContainer.getHost() - const mappedPort = temporalContainer.getMappedPort(7233) - const address = `${host}:${mappedPort}` + const host = temporalContainer.getHost() + const mappedPort = temporalContainer.getMappedPort(7233) + const address = `${host}:${mappedPort}` - process.env.TEMPORAL_ADDRESS = address - console.log(`Temporal Dev Server container started. Address: ${address}`) + process.env.TEMPORAL_ADDRESS = address + console.log(`Temporal Dev Server container started. Address: ${address}`) - // Brief sleep to ensure temporal dev server is fully ready to accept gRPC clients - await new Promise((resolve) => setTimeout(resolve, 2000)) - } catch (err) { - console.error('Failed to start Temporal Dev Server container:', err) - throw err - } + // Brief sleep to ensure temporal dev server is fully ready to accept gRPC clients + await new Promise((resolve) => setTimeout(resolve, 2000)) + } catch (err) { + console.error('Failed to start Temporal Dev Server container:', err) + throw err } } diff --git a/packages/workflow-core/src/workflow-workers.test.ts b/packages/workflow-core/src/workflow-workers.test.ts index e53670b5..733af2d7 100644 --- a/packages/workflow-core/src/workflow-workers.test.ts +++ b/packages/workflow-core/src/workflow-workers.test.ts @@ -26,16 +26,12 @@ describe('WorkflowService Temporal Workers Concurrency Control', () => { originalExecutor = process.env.WORKFLOW_EXECUTOR originalTranscode = process.env.CONCURRENCY_TRANSCODE originalAgent = process.env.CONCURRENCY_AGENT - process.env.WORKFLOW_EXECUTOR = 'temporal' + workflowService.setExecutorType('temporal') vi.clearAllMocks() }) afterEach(() => { - if (originalExecutor === undefined) { - delete process.env.WORKFLOW_EXECUTOR - } else { - process.env.WORKFLOW_EXECUTOR = originalExecutor - } + workflowService.setExecutorType(originalExecutor === 'temporal' ? 'temporal' : 'local') if (originalTranscode === undefined) { delete process.env.CONCURRENCY_TRANSCODE diff --git a/packages/workflow-core/src/workflow.ts b/packages/workflow-core/src/workflow.ts index e80fb644..1eed7b1b 100644 --- a/packages/workflow-core/src/workflow.ts +++ b/packages/workflow-core/src/workflow.ts @@ -20,6 +20,14 @@ export class WorkflowService { } } + setExecutorType(type: 'local' | 'temporal') { + if (type === 'temporal') { + this.executor = new TemporalExecutor(process.env.TEMPORAL_ADDRESS) + } else { + this.executor = new LocalExecutor() + } + } + async submit(task: WorkflowTask): Promise { return this.executor.submit(task) } @@ -77,7 +85,7 @@ export class WorkflowService { queue: string, options: { workflowBundle?: unknown; workflowsPath?: string } = {}, ): Promise { - const type = process.env.WORKFLOW_EXECUTOR || 'local' + const type = this.executor instanceof TemporalExecutor ? 'temporal' : 'local' if (type === 'temporal') { const { Worker, NativeConnection } = await import('@temporalio/worker') diff --git a/vitest.config.ts b/vitest.config.ts index f5664142..1cac6d55 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -7,9 +7,12 @@ export default defineConfig({ globalSetup: './packages/db/src/test-global-setup.ts', globals: false, pool: 'forks', - // Playwright e2e specs live under packages/webui/e2e and are run by the - // Playwright runner (bun run test:e2e), not Vitest. - exclude: [...configDefaults.exclude, 'packages/webui/e2e/**', 'apps/web/e2e/**'], + exclude: [ + ...configDefaults.exclude, + 'packages/webui/e2e/**', + 'apps/web/e2e/**', + 'packages/e2e/**', + ], server: { deps: { inline: ['zod', '@shumai/workflow-core', '@temporalio/activity'], From 7d9f3276f11fb09476e6f117bf419951d12536c4 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 15 Jul 2026 11:54:29 +0800 Subject: [PATCH 4/6] test(e2e): verify multiple types in autofill and check that non-autofill field is ignored --- packages/e2e/workflow/agent-autofill.test.ts | 91 ++++++++++++++++++-- 1 file changed, 86 insertions(+), 5 deletions(-) diff --git a/packages/e2e/workflow/agent-autofill.test.ts b/packages/e2e/workflow/agent-autofill.test.ts index 122d7477..5a839cb2 100644 --- a/packages/e2e/workflow/agent-autofill.test.ts +++ b/packages/e2e/workflow/agent-autofill.test.ts @@ -40,7 +40,11 @@ describe.each(['local', 'temporal'] as const)('Workflow E2E - agentAutofillMedia if (autofillTool) { // Execute the real tool callback to perform the actual DB updates - await autofillTool.execute('call-123', { title: 'E2E Title Extracted' }) + await autofillTool.execute('call-123', { + title: 'E2E Title Extracted', + confidence: 0.95, + completed: true, + }) } // Return a successful assistant response mock @@ -101,7 +105,7 @@ describe.each(['local', 'temporal'] as const)('Workflow E2E - agentAutofillMedia data: { name: 'E2E Test Project', teamId: team.id }, }) - // Create Metadata Field (aiAutofill = true) + // Create Metadata Field (aiAutofill = true, text) await prisma.metadataField.create({ data: { key: 'title', @@ -114,6 +118,45 @@ describe.each(['local', 'temporal'] as const)('Workflow E2E - agentAutofillMedia }, }) + // Create Metadata Field (aiAutofill = true, number) + await prisma.metadataField.create({ + data: { + key: 'confidence', + scope: 'PROJECT', + projectId: project.id, + teamId: team.id, + config: { name: 'Confidence', type: 'number' }, + aiAutofill: true, + description: 'AI extraction confidence', + }, + }) + + // Create Metadata Field (aiAutofill = true, boolean) + await prisma.metadataField.create({ + data: { + key: 'completed', + scope: 'PROJECT', + projectId: project.id, + teamId: team.id, + config: { name: 'Completed', type: 'toggle' }, + aiAutofill: true, + description: 'Completed flag', + }, + }) + + // Create Metadata Field (aiAutofill = false, text) + await prisma.metadataField.create({ + data: { + key: 'manual_notes', + scope: 'PROJECT', + projectId: project.id, + teamId: team.id, + config: { name: 'Manual Notes', type: 'text' }, + aiAutofill: false, + description: 'Manual notes (should not be auto-filled)', + }, + }) + // Create Agent User const agentUser = await prisma.user.create({ data: { @@ -235,7 +278,7 @@ describe.each(['local', 'temporal'] as const)('Workflow E2E - agentAutofillMedia expect(finalComment.message).toBe('Autofill completed successfully.') // Verify AssetMetadataValue contains the AI-extracted title - const metadataValue = await prisma.assetMetadataValue.findUnique({ + const titleVal = await prisma.assetMetadataValue.findUnique({ where: { // eslint-disable-next-line @typescript-eslint/naming-convention assetId_fieldKey: { @@ -244,7 +287,45 @@ describe.each(['local', 'temporal'] as const)('Workflow E2E - agentAutofillMedia }, }, }) - expect(metadataValue).toBeDefined() - expect(metadataValue?.stringValue).toBe('E2E Title Extracted') + expect(titleVal).toBeDefined() + expect(titleVal?.stringValue).toBe('E2E Title Extracted') + + // Verify AssetMetadataValue contains the AI-extracted confidence + const confidenceVal = await prisma.assetMetadataValue.findUnique({ + where: { + // eslint-disable-next-line @typescript-eslint/naming-convention + assetId_fieldKey: { + assetId: asset.id, + fieldKey: 'confidence', + }, + }, + }) + expect(confidenceVal).toBeDefined() + expect(confidenceVal?.numberValue).toBe(0.95) + + // Verify AssetMetadataValue contains the AI-extracted completed flag + const completedVal = await prisma.assetMetadataValue.findUnique({ + where: { + // eslint-disable-next-line @typescript-eslint/naming-convention + assetId_fieldKey: { + assetId: asset.id, + fieldKey: 'completed', + }, + }, + }) + expect(completedVal).toBeDefined() + expect(completedVal?.booleanValue).toBe(true) + + // Verify manual_notes is NOT auto-filled (remains null/undefined in DB) + const manualNotesVal = await prisma.assetMetadataValue.findUnique({ + where: { + // eslint-disable-next-line @typescript-eslint/naming-convention + assetId_fieldKey: { + assetId: asset.id, + fieldKey: 'manual_notes', + }, + }, + }) + expect(manualNotesVal).toBeNull() }, 50000) }) From c6acd075e7c74de41d3191dfb2f59eae0ea7a544 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 15 Jul 2026 11:58:17 +0800 Subject: [PATCH 5/6] refactor(workflow-core): statically import Worker type from @temporalio/worker to ensure activeWorkers type-safety --- packages/workflow-core/src/workflow.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/workflow-core/src/workflow.ts b/packages/workflow-core/src/workflow.ts index 1eed7b1b..18050706 100644 --- a/packages/workflow-core/src/workflow.ts +++ b/packages/workflow-core/src/workflow.ts @@ -7,9 +7,11 @@ import { LocalExecutor } from './local-executor' import { TemporalExecutor } from './temporal-executor' import { TaskQueueAgent, TaskQueueTranscode, getConcurrencyLimit } from './workflow-utils' +import type { Worker } from '@temporalio/worker' + export class WorkflowService { private executor: Executor - private activeWorkers: unknown[] = [] + private activeWorkers: Worker[] = [] constructor() { const type = process.env.WORKFLOW_EXECUTOR || 'local' @@ -74,9 +76,7 @@ export class WorkflowService { } async shutdownWorkers(): Promise { - await Promise.all( - this.activeWorkers.map((w) => (w as { shutdown: () => Promise }).shutdown()), - ) + await Promise.all(this.activeWorkers.map((w) => w.shutdown())) this.activeWorkers = [] } From 6f369625d8edd39d81d8d247f759b411bdf82015 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 15 Jul 2026 12:03:17 +0800 Subject: [PATCH 6/6] docs(agents): update AGENTS.md with E2E workflow testing requirements --- AGENTS.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 510b1631..3fd46542 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -91,6 +91,7 @@ Add any additional context, caveats, or follow-up work. - `bun run typecheck` - `bun run test` - `bun run test:e2e` + - `bun run test:e2e:workflow` - **Backend Testing Mandate**: Every backend feature, service method, workflow, and activity MUST be accompanied by comprehensive tests. Logic-heavy code without corresponding test coverage is considered incomplete. @@ -273,6 +274,14 @@ describe('Team API', () => { }) ``` +### Workflow E2E Tests + +- Located in `packages/e2e/workflow/**/*.test.ts`. +- Run via `bun run test:e2e:workflow` (which executes tests against both `local` and `temporal` executors dynamically). +- **Mandatory test coverage**: When creating or updating workflows or activities, you MUST create or update the corresponding E2E tests. +- **Mocking**: Mock ONLY AI API calls. Do not mock S3, databases, or media/transcode extraction services. +- Mock the AI response by spying on `AgentHarness.prototype.prompt`: + ## Prisma Configuration & Migrations - Schema: `packages/db/prisma/schema.prisma`