Files
elizaos--eliza/plugins/plugin-workflow/__tests__/integration/routes-e2e.test.ts
T
wehub-resource-sync 426e9eeabd
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
ci / test (push) Has been cancelled
ci / lint-and-format (push) Has been cancelled
ci / build (push) Has been cancelled
ci / dev-startup (push) Has been cancelled
gitleaks / gitleaks (push) Has been cancelled
Markdown Links / Relative Markdown Links (push) Has been cancelled
Quality (Extended) / Homepage Build (PR smoke) (push) Has been cancelled
Quality (Extended) / Comment-only diff guard (push) Has been cancelled
Quality (Extended) / Format + Type Safety Ratchet (push) Has been cancelled
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Has been cancelled
Quality (Extended) / Develop Gate (lint) (push) Has been cancelled
Chat shell gestures / Chat shell gesture + parity e2e (push) Has been cancelled
Cloud Gateway Discord / Test (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Has been cancelled
Build Agent Image / build-and-push (push) Has been cancelled
Dev Smoke / bun run dev onboarding chat (push) Has been cancelled
Dev Smoke / Vite HMR dependency-level smoke (push) Has been cancelled
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Has been cancelled
Publish @elizaos/example-code / check_npm (push) Has been cancelled
Publish @elizaos/example-code / publish_npm (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / verify_version (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / publish_npm (push) Has been cancelled
Sandbox Live Smoke / Sandbox live smoke (push) Has been cancelled
Snap Build & Test / Build Snap (amd64) (push) Has been cancelled
Snap Build & Test / Build Snap (arm64) (push) Has been cancelled
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Has been cancelled
Cloud Gateway Webhook / Test (push) Has been cancelled
Cloud Tests / lint-and-types (push) Has been cancelled
Cloud Tests / unit-tests (push) Has been cancelled
Cloud Tests / integration-tests (push) Has been cancelled
Cloud Tests / e2e-tests (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Apps Worker (Product 2) / Determine environment (push) Has been cancelled
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Has been cancelled
Deploy Eliza Provisioning Worker / Determine environment (push) Has been cancelled
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Has been cancelled
Dev Smoke / Classify changed paths (push) Has been cancelled
supply-chain / sbom (push) Has been cancelled
supply-chain / vulnerability-scan (push) Has been cancelled
Build, Push & Deploy to Phala Cloud / build-and-push (push) Has been cancelled
Test Packaging / Validate Packaging Configs (push) Has been cancelled
Test Packaging / Build & Test PyPI Package (push) Has been cancelled
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Has been cancelled
Test Packaging / Pack & Test JS Tarballs (push) Has been cancelled
UI Fixture E2E / ui-fixture-e2e (push) Has been cancelled
UI Fixture E2E / fixture-e2e (push) Has been cancelled
UI Story Gate / story-gate (push) Has been cancelled
vault-ci / test (macos-latest) (push) Has been cancelled
vault-ci / test (ubuntu-latest) (push) Has been cancelled
vault-ci / test (windows-latest) (push) Has been cancelled
vault-ci / app-core wiring tests (push) Has been cancelled
verify-patches / verify patches/CHECKSUMS.sha256 (push) Has been cancelled
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Has been cancelled
Voice Benchmark Smoke / voice bench smoke summary (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Has been cancelled
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:43:05 +08:00

212 lines
7.6 KiB
TypeScript

/**
* Route-level e2e for plugin-workflow (issue #8802).
*
* Boots the plugin's declared `workflowRoutes` through the real production
* dispatcher (`tryHandleRuntimePluginRoute`) over a loopback `http.createServer`
* — exercising the real auth gate, JSON body parsing, query/param parsing, and
* handler dispatch — with a faked `WorkflowService` standing in for the only
* external dependency. No mocked `json`/`status`: every assertion is on a real
* HTTP response (status + parsed body).
*/
import { afterEach, describe, expect, test } from 'bun:test';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import type { AgentRuntime } from '@elizaos/core';
import { tryHandleRuntimePluginRoute } from '../../../../packages/agent/src/api/runtime-plugin-routes';
import { workflowRoutes } from '../../src/routes/index';
import { createValidWorkflow, createWorkflowResponse } from '../fixtures/workflows';
const servers: http.Server[] = [];
afterEach(async () => {
await Promise.all(
servers.map(
(server) =>
new Promise<void>((resolve) => {
server.closeAllConnections?.();
server.close(() => resolve());
})
)
);
servers.length = 0;
});
interface ServiceCall {
method: string;
args: unknown[];
}
interface FakeServiceState {
calls: ServiceCall[];
}
/**
* Build a fake `WorkflowService` covering only the methods the routes call.
* Returns deterministic, JSON-serializable fixtures so the real HTTP round-trip
* can be asserted end to end.
*/
function makeWorkflowService(state: FakeServiceState) {
const record =
(method: string, result: unknown) =>
(...args: unknown[]) => {
state.calls.push({ method, args });
return Promise.resolve(result);
};
return {
listWorkflows: record('listWorkflows', [
createWorkflowResponse({ id: 'wf-001', name: 'Workflow A', active: true }),
createWorkflowResponse({ id: 'wf-002', name: 'Workflow B', active: false }),
]),
getWorkflow: record('getWorkflow', createWorkflowResponse({ id: 'wf-001' })),
deployWorkflow: record('deployWorkflow', {
id: 'wf-001',
name: 'Test Workflow',
active: true,
nodeCount: 2,
missingCredentials: [],
}),
activateWorkflow: record('activateWorkflow', undefined),
deactivateWorkflow: record('deactivateWorkflow', undefined),
deleteWorkflow: record('deleteWorkflow', undefined),
listExecutions: record('listExecutions', {
data: [{ id: 'exec-001', status: 'success', workflowId: 'wf-001' }],
nextCursor: undefined,
}),
getExecutionDetail: record('getExecutionDetail', {
id: 'exec-001',
status: 'success',
workflowId: 'wf-001',
}),
};
}
function makeRuntime(
options: { withService?: boolean; state?: FakeServiceState } = {}
): AgentRuntime {
const { withService = true, state } = options;
const service = state ? makeWorkflowService(state) : makeWorkflowService({ calls: [] });
return {
routes: workflowRoutes,
// The WorkflowService key is "workflow" (WORKFLOW_SERVICE_TYPE).
getService: (key: string) => (withService && key === 'workflow' ? service : null),
} as unknown as AgentRuntime;
}
async function startServer(
runtime: AgentRuntime,
isAuthorized: () => boolean = () => true
): Promise<string> {
const server = http.createServer(async (req, res) => {
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
const handled = await tryHandleRuntimePluginRoute({
req,
res,
method: req.method ?? 'GET',
pathname: url.pathname,
url,
runtime,
isAuthorized,
});
if (!handled && !res.headersSent) {
res.statusCode = 404;
res.end('not found');
}
});
servers.push(server);
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
return `http://127.0.0.1:${port}`;
}
async function postJson(base: string, path: string, body: unknown) {
return fetch(`${base}${path}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
}
describe('plugin-workflow routes (real dispatch)', () => {
// NOTE: workflow CRUD (list/create/get/update/delete/activate/deactivate) is
// served canonically by the rawPath `/api/workflow/*` surface
// (routes/workflow-routes.ts) and tested there. The former plugin-relative
// `/workflows*` CRUD duplicate was removed in #12177; the relative surfaces
// exercised below (executions, validate) have no rawPath twin and stay here.
test('GET /executions lists executions and forwards query params', async () => {
const state: FakeServiceState = { calls: [] };
const base = await startServer(makeRuntime({ state }));
const res = await fetch(`${base}/executions?workflowId=wf-001&status=success&limit=10`);
expect(res.status).toBe(200);
const body = (await res.json()) as {
success: boolean;
data: Array<{ id: string }>;
};
expect(body.success).toBe(true);
expect(body.data[0].id).toBe('exec-001');
const call = state.calls.find((c) => c.method === 'listExecutions');
expect(call?.args[0]).toMatchObject({ workflowId: 'wf-001', status: 'success', limit: 10 });
});
test('GET /executions/:id returns execution detail', async () => {
const state: FakeServiceState = { calls: [] };
const base = await startServer(makeRuntime({ state }));
const res = await fetch(`${base}/executions/exec-001`);
expect(res.status).toBe(200);
const body = (await res.json()) as { success: boolean; data: { id: string } };
expect(body.success).toBe(true);
expect(body.data.id).toBe('exec-001');
const call = state.calls.find((c) => c.method === 'getExecutionDetail');
expect(call?.args[0]).toBe('exec-001');
});
test('POST /workflows/validate runs the real validator without a service', async () => {
// The validate handler never touches WorkflowService, so it must succeed
// even when the service is unavailable.
const base = await startServer(makeRuntime({ withService: false }));
const valid = await postJson(base, '/workflows/validate', createValidWorkflow());
expect(valid.status).toBe(200);
expect((await valid.json()) as { valid: boolean }).toMatchObject({ valid: true });
const invalid = await postJson(base, '/workflows/validate', {
name: 'Empty',
nodes: [],
connections: {},
});
expect(invalid.status).toBe(200);
const invalidBody = (await invalid.json()) as { valid: boolean; errors: string[] };
expect(invalidBody.valid).toBe(false);
expect(invalidBody.errors.length).toBeGreaterThan(0);
// Missing the required `nodes` field → 400 from the real handler guard.
const malformed = await postJson(base, '/workflows/validate', { connections: {} });
expect(malformed.status).toBe(400);
expect((await malformed.json()) as { success: boolean }).toMatchObject({ success: false });
});
test('enforces the auth gate on the non-public workflow routes', async () => {
// Every plugin-workflow route is auth-gated (none declare `public: true`),
// so a denied authorization yields 401 before any handler runs.
const base = await startServer(makeRuntime(), () => false);
const list = await fetch(`${base}/executions`);
expect(list.status).toBe(401);
expect((await list.json()) as { error: string }).toMatchObject({ error: 'Unauthorized' });
});
test('returns 404 for an unknown route path', async () => {
const base = await startServer(makeRuntime());
const res = await fetch(`${base}/nonexistent-workflow-subroute`);
expect(res.status).toBe(404);
});
});