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/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` diff --git a/bun.lock b/bun.lock index 9fe0e9b9..1d06ec5f 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,32 @@ }, "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": { + "@earendil-works/pi-agent-core": "0.78.0", + "@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 +217,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 +314,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 +1023,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..11905fd2 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": "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..104b50c6 --- /dev/null +++ b/packages/e2e/package.json @@ -0,0 +1,15 @@ +{ + "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:*", + "@earendil-works/pi-agent-core": "0.78.0" + } +} 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..5a839cb2 --- /dev/null +++ b/packages/e2e/workflow/agent-autofill.test.ts @@ -0,0 +1,331 @@ +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' + +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.each(['local', 'temporal'] as const)('Workflow E2E - agentAutofillMedia (executor: %s)', (mode) => { + setupTestDbHooks() + + let agentWorkerPromise: Promise | null = null + let transcodeWorkerPromise: Promise | null = null + + beforeAll(async () => { + // Set bucket environment + process.env.S3_BUCKET = 'shumai-e2e-test-bucket' + + // Configure the workflow service executor dynamically + workflowService.setExecutorType(mode) + + // Initialize registries + initAgentWorkflows() + initTranscodeWorkflows() + + // 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', + confidence: 0.95, + completed: true, + }) + } + + // 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 */ + }) + + if (mode === '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 () => { + if (mode === 'temporal') { + console.log('Shutting down Temporal workers...') + await workflowService.shutdownWorkers() + await Promise.all([agentWorkerPromise, transcodeWorkerPromise].filter(Boolean)) + } + + workflowService.close() + + // Restore spied methods + vi.restoreAllMocks() + + // 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, text) + 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 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: { + 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 titleVal = await prisma.assetMetadataValue.findUnique({ + where: { + // eslint-disable-next-line @typescript-eslint/naming-convention + assetId_fieldKey: { + assetId: asset.id, + fieldKey: 'title', + }, + }, + }) + 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) +}) diff --git a/packages/e2e/workflow/test-global-setup.ts b/packages/e2e/workflow/test-global-setup.ts new file mode 100644 index 00000000..ca6c41ec --- /dev/null +++ b/packages/e2e/workflow/test-global-setup.ts @@ -0,0 +1,47 @@ +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 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}` + + 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-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 94655db6..18050706 100644 --- a/packages/workflow-core/src/workflow.ts +++ b/packages/workflow-core/src/workflow.ts @@ -7,8 +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: Worker[] = [] constructor() { const type = process.env.WORKFLOW_EXECUTOR || 'local' @@ -19,6 +22,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) } @@ -64,12 +75,17 @@ export class WorkflowService { this.executor.close() } + async shutdownWorkers(): Promise { + await Promise.all(this.activeWorkers.map((w) => w.shutdown())) + this.activeWorkers = [] + } + // Starts Temporal workers for specific task queues async startWorkers( 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') @@ -156,6 +172,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"] 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'],