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"]