import { execFileSync } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { PassThrough } from 'node:stream'; import * as OTPAuth from 'otpauth'; import type { ClientChannel } from 'ssh2'; import { afterEach, describe, expect, it, vi } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; const cleanups: Array<() => Promise | void> = []; class CookieJar { private cookies = new Map(); updateFrom(res: Response): void { const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie; const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : []; for (const line of rawList) { const first = line.split(';')[0] ?? ''; const eq = first.indexOf('='); if (eq > 0) { const name = first.slice(0, eq).trim(); const val = first.slice(eq + 1).trim(); if (val === '') this.cookies.delete(name); else this.cookies.set(name, val); } } } header(): string { return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; '); } } async function openWs(url: string, headers: Record) { return new Promise<{ ws: WebSocket; frames: Array> }>((resolve, reject) => { const frames: Array> = []; const ws = new WebSocket(url, { headers }); ws.on('message', (raw) => frames.push(JSON.parse(raw.toString()))); ws.once('open', () => resolve({ ws, frames })); ws.once('unexpected-response', (_req, res) => reject(new Error(`WS_HTTP_${res.statusCode}`)), ); ws.once('error', reject); }); } async function waitFor( fn: () => Promise | T | undefined | null | false, timeoutMs = 5000, intervalMs = 30, ): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const val = await fn(); if (val) return val; await new Promise((r) => setTimeout(r, intervalMs)); } throw new Error('Timed out waiting for condition'); } async function waitForWorkflowRun(server: GCoordinatorInstance, runId: string, timeoutMs = 4000) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const detail = server.workflowEngine.getRunDetail(runId); if (detail && detail.run.status !== 'running' && detail.run.status !== 'queued') { return detail; } await new Promise((r) => setTimeout(r, 30)); } const latest = server.workflowEngine.getRunDetail(runId); const streamFrames = server.workflowEngine.getStreamReplayFrames(`wf:${runId}`); throw new Error( `Workflow run ${runId} timed out: run=${JSON.stringify(latest?.run)} steps=${JSON.stringify(latest?.stepLogs)} frames=${JSON.stringify(streamFrames.slice(-10))}`, ); } afterEach(async () => { while (cleanups.length > 0) { await cleanups.pop()!(); } }); describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers', () => { it( 'supports Snippets CRUD, Safe Mode blocks, Ad-Hoc Fleet Broadcast with safe shell quoting, WS streaming & cancel, Full DAG + steps + transfers, Overlap policies, Timeouts, and Cron', { timeout: 25_000 }, async () => { const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p4-wf-')); const sftpRootA = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p4-sftpa-')); const sftpRootB = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p4-sftpb-')); fs.mkdirSync(path.join(sftpRootA, 'logs'), { recursive: true }); fs.writeFileSync(path.join(sftpRootA, 'logs', 'app.log'), 'l1\nl2\nl3\nl4\n'); fs.writeFileSync(path.join(sftpRootA, 'single.txt'), 'single-file-payload\n'); fs.mkdirSync(path.join(sftpRootA, 'bundle', 'nested'), { recursive: true }); fs.writeFileSync(path.join(sftpRootA, 'bundle', 'top.txt'), 'top-content'); fs.writeFileSync(path.join(sftpRootA, 'bundle', 'nested', 'deep.txt'), 'deep-content'); const seenExecA: string[] = []; const seenExecB: string[] = []; const directRsyncCmds: string[] = []; const server = await createGCoordinatorServer({ dataDir, port: 0, host: '127.0.0.1', publicDir: path.resolve('dist/public'), watchConfig: false, }); cleanups.push(async () => { await server.close(); fs.rmSync(dataDir, { recursive: true, force: true }); fs.rmSync(sftpRootA, { recursive: true, force: true }); fs.rmSync(sftpRootB, { recursive: true, force: true }); }); const baseUrl = `http://127.0.0.1:${server.port}`; const wsUrl = `ws://127.0.0.1:${server.port}/ws`; const jar = new CookieJar(); let csrfToken = ''; const api = async ( pathname: string, opts: { method?: string; body?: unknown; safeMode?: boolean } = {}, ) => { const headers: Record = {}; if (jar.header()) headers.Cookie = jar.header(); if (opts.body !== undefined) headers['Content-Type'] = 'application/json'; if (csrfToken) headers['X-CSRF-Token'] = csrfToken; if (opts.safeMode) headers['X-GCoord-Safe-Mode'] = '1'; const res = await fetch(`${baseUrl}${pathname}`, { method: opts.method ?? 'GET', headers, body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, }); jar.updateFrom(res); const data = (await res.json().catch(() => ({}))) as Record; return { status: res.status, data }; }; vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ issuer: 'GCoordinator', label: 'admin', algorithm: 'SHA1', digits: 6, period: 30, secret: OTPAuth.Secret.fromBase32(secretBase32), }); const boot = await api('/api/auth/bootstrap', { method: 'POST', body: { username: 'admin', password: 'phase4-workflow-password', totpCode: totp.generate(), secretBase32, initialSafeMode: false, }, }); vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); expect( (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { method: 'POST', body: { id: 'wf-key', name: 'Workflow Key' }, }); const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey); await api('/api/vault/credentials', { method: 'POST', body: { id: 'wf-sudo', name: 'WF Sudo', type: 'sudo-password', password: 'sudo-wf-pw', }, }); const makeMockExec = (serverTag: 'A' | 'B', sink: string[]) => (cmd: string) => { sink.push(cmd); if (cmd.includes('REAL_SH_QUOTE_TEST')) { const out = execFileSync('/bin/sh', ['-c', cmd], { encoding: 'utf8' }); return { stdout: out, exitCode: 0 }; } if (cmd.includes('systemctl list-units')) { return { stdout: 'nginx.service\n', exitCode: 0 }; } if (cmd.includes('systemctl show')) { return { stdout: JSON.stringify({ Id: 'nginx.service', LoadState: 'loaded', ActiveState: 'active', SubState: 'running', }), exitCode: 0, }; } if (cmd.includes('systemctl restart')) { return { stdout: `restarted nginx on ${serverTag}\n`, exitCode: 0 }; } if (cmd.includes('rsync -az ')) { directRsyncCmds.push(cmd); return { stdout: 'sent 128 bytes\n', exitCode: 0 }; } if (cmd.includes('FAIL_NOW')) { return { stdout: '', stderr: 'intentional step failure', exitCode: 42 }; } if (cmd.includes('PRINT_CAP')) { const out = execFileSync('/bin/sh', ['-c', cmd], { encoding: 'utf8' }); return { stdout: out, exitCode: 0 }; } if (cmd.includes('CRON_TICK')) { return { stdout: `cron-ok-${serverTag}\n`, exitCode: 0 }; } if (cmd.includes('ECHO_STEP')) { const out = execFileSync('/bin/sh', ['-c', cmd], { encoding: 'utf8' }); return { stdout: out, exitCode: 0 }; } return { stdout: `ok:${serverTag}\n`, exitCode: 0 }; }; const mockA = new MockSshServer({ username: 'ops', os: 'Linux', sudoPassword: 'sudo-wf-pw', authorizedKeys: [pubKey], sftpRootDir: sftpRootA, onExec: makeMockExec('A', seenExecA), }); const mockB = new MockSshServer({ username: 'ops', os: 'Linux', sudoPassword: 'sudo-wf-pw', authorizedKeys: [pubKey], sftpRootDir: sftpRootB, onExec: makeMockExec('B', seenExecB), }); const portA = await mockA.start(); const portB = await mockB.start(); cleanups.push(async () => { await mockA.close(); await mockB.close(); }); await api('/api/servers', { method: 'POST', body: { id: 'srv-a', name: 'Server A', host: '127.0.0.1', port: portA, username: 'ops', credentialId: 'wf-key', sudoCredentialId: 'wf-sudo', tags: ['web'], pollIntervalSec: 3600, }, }); await api('/api/servers', { method: 'POST', body: { id: 'srv-b', name: 'Server B', host: '127.0.0.1', port: portB, username: 'ops', credentialId: 'wf-key', sudoCredentialId: 'wf-sudo', tags: ['backup'], pollIntervalSec: 3600, }, }); await api('/api/servers/srv-a/reconnect', { method: 'POST' }); await api('/api/servers/srv-b/reconnect', { method: 'POST' }); expect( ( await api('/api/servers/srv-a/tofu/approve', { method: 'POST', body: { fingerprint: mockA.hostFingerprint }, }) ).status, ).toBe(200); expect( ( await api('/api/servers/srv-b/tofu/approve', { method: 'POST', body: { fingerprint: mockB.hostFingerprint }, }) ).status, ).toBe(200); await waitFor( () => server.sshPool.getState('srv-a')?.status === 'connected' && server.sshPool.getState('srv-b')?.status === 'connected', ); // Attach systemd to srv-a for system-action step expect( ( await api('/api/systems/systemd/servers/srv-a/attach', { method: 'PUT', body: { params: { unitFilter: 'nginx' } }, }) ).status, ).toBe(200); // Wrap execStream ONLY for deterministic slow steps (__SLOW_250__ / __SLOW_2S__) const origExecStream = server.sshPool.execStream.bind(server.sshPool); vi.spyOn(server.sshPool, 'execStream').mockImplementation(async (serverId, cmd, opts) => { if (!cmd.includes('__SLOW_')) { return origExecStream(serverId, cmd, opts); } const ch = new PassThrough() as PassThrough & { stderr: PassThrough; close: () => void }; const stderrStream = new PassThrough(); ch.stderr = stderrStream; let timer: NodeJS.Timeout | undefined; let settled = false; let resolveDone!: (res: { exitCode: number | null; signal?: string }) => void; const done = new Promise<{ exitCode: number | null; signal?: string }>((resolve) => { resolveDone = resolve; }); const finish = (res: { exitCode: number | null; signal?: string }) => { if (settled) return; settled = true; if (timer) clearTimeout(timer); ch.end(); stderrStream.end(); resolveDone(res); }; const abort = () => { finish({ exitCode: null, signal: 'TERM' }); }; ch.close = abort; const delayMs = cmd.includes('__SLOW_2S__') ? 2500 : 300; ch.write(`slow-start:${serverId}\n`); timer = setTimeout(() => { ch.write(`slow-end:${serverId}\n`); finish({ exitCode: 0 }); }, delayMs); return { channel: ch as unknown as ClientChannel, done, abort }; }); // --- 1. Snippets CRUD & Safe Mode enforcement --- const safeBlocked = await api('/api/snippets', { method: 'POST', safeMode: true, body: { id: 'snip-safe', name: 'Safe', command: 'echo hi' }, }); expect(safeBlocked.status).toBe(423); expect(safeBlocked.data.error).toBe('SAFE_MODE_ACTIVE'); const snipCreate = await api('/api/snippets', { method: 'POST', body: { id: 'snip-quote', name: 'Safe Quoting Check', command: 'echo REAL_SH_QUOTE_TEST && printf "ARG=%s ENV=%s" {{inputs.arg}} "$GCOORD_INPUT_ARG"', tags: ['diagnostics'], inputs: [{ name: 'arg', type: 'string', required: true }], sudo: false, confirm: false, }, }); expect(snipCreate.status).toBe(201); const snipDup = await api('/api/snippets', { method: 'POST', body: { id: 'snip-quote', name: 'Dup', command: 'echo dup' }, }); expect(snipDup.status).toBe(409); const snipUpd = await api('/api/snippets/snip-quote', { method: 'PUT', body: { name: 'Safe Quoting Updated', command: 'echo REAL_SH_QUOTE_TEST && printf "ARG=%s|ENV=%s" {{inputs.arg}} "$GCOORD_INPUT_ARG"', tags: ['diagnostics'], inputs: [{ name: 'arg', type: 'string', required: true }], sudo: false, confirm: false, }, }); expect(snipUpd.status).toBe(200); expect( ((await api('/api/snippets')).data.snippets as Array<{ id: string }>).some( (s) => s.id === 'snip-quote', ), ).toBe(true); // Temporary snippet to verify DELETE await api('/api/snippets', { method: 'POST', body: { id: 'snip-del', name: 'Temp', command: 'echo bye' }, }); expect((await api('/api/snippets/snip-del', { method: 'DELETE' })).status).toBe(200); // --- 2. Ad-Hoc Fleet Broadcast (safe quoting, WS replay, cancellation) --- const dangerousArg = "hello'; touch /tmp/should-not-run; echo INJECTED"; const { ws, frames } = await openWs(wsUrl, { Cookie: jar.header(), Host: `127.0.0.1:${server.port}`, Origin: baseUrl, }); cleanups.push(() => ws.close()); const bcastRes = await api('/api/workflows/broadcast', { method: 'POST', body: { snippetId: 'snip-quote', inputs: { arg: dangerousArg }, concurrency: 2, target: { all: true }, }, }); expect(bcastRes.status).toBe(202); const jobId = String((bcastRes.data.job as { jobId: string }).jobId); const bcastDone = await waitFor(async () => { const g = await api(`/api/workflows/broadcast/${jobId}`); const j = g.data.job as { done: boolean; targets: Array<{ serverId: string; stdout: string; exitCode: number | null; status: string }>; }; return j?.done ? j : undefined; }); expect(bcastDone.targets).toHaveLength(2); for (const t of bcastDone.targets) { expect(t.status).toBe('ok'); expect(t.exitCode).toBe(0); // POSIX single-quoting prevents shell injection; literal payload reaches printf unchanged expect(t.stdout).toContain(`ARG=${dangerousArg}|ENV=${dangerousArg}`); expect(t.stdout).not.toContain('\nINJECTED'); } // Subscribe AFTER broadcast finished to verify BufferedStreamEmitter replay frames ws.send(JSON.stringify({ type: 'sub', channels: [`stream:${jobId}`] })); await waitFor(() => frames.some((f) => { if (f.type !== 'stream:chunk' || f.jobId !== jobId || f.stream !== 'meta') return false; try { return (JSON.parse(String(f.data)) as { event?: string }).event === 'done'; } catch { return false; } }), ); // Broadcast cancellation const slowBcast = await api('/api/workflows/broadcast', { method: 'POST', body: { command: 'echo __SLOW_2S__', target: { serverId: 'srv-a' }, }, }); expect(slowBcast.status).toBe(202); const slowJobId = String((slowBcast.data.job as { jobId: string }).jobId); const cancelBcast = await api(`/api/workflows/broadcast/${slowJobId}/cancel`, { method: 'POST', }); expect(cancelBcast.status).toBe(200); expect(cancelBcast.data.cancelled).toBe(true); const abortedJob = await waitFor(() => { const j = server.broadcastService.getBroadcastResult(slowJobId); return j?.done ? j : undefined; }); expect(abortedJob.cancelled).toBe(true); expect(abortedJob.targets[0]?.status).toBe('cancelled'); // --- 3. Workflow Dry-Run, Pinned summary, Full DAG + failure/always + read-file + system-action + hub-relayed & direct transfers --- const dagWf = { id: 'wf-dag-full', name: 'Full DAG Verification', enabled: true, trigger: { type: 'manual' }, overlapPolicy: 'skip', stopOnError: false, concurrency: 2, display: { mode: 'summary', pinToDashboard: true }, inputs: [{ name: 'tag', type: 'string', required: true }], steps: [ { id: 'gen-token', type: 'exec', target: { serverId: 'srv-a' }, command: ': ECHO_STEP; printf "tok-%s" {{inputs.tag}}', captureAs: 'tok', }, { id: 'tail-log', type: 'read-file', target: { serverId: 'srv-a' }, path: '/logs/app.log', tailLines: 2, }, { id: 'svc-restart', type: 'system-action', dependsOn: ['gen-token'], target: { serverId: 'srv-a' }, systemId: 'systemd', action: 'restart', item: 'nginx.service', }, { id: 'xfer-file', type: 'transfer', dependsOn: ['gen-token'], mode: 'hub-relayed', source: { serverId: 'srv-a', path: '/single.txt' }, destination: { serverId: 'srv-b', path: '/dst-single.txt' }, }, { id: 'xfer-dir', type: 'transfer', dependsOn: ['xfer-file'], mode: 'hub-relayed', source: { serverId: 'srv-a', path: '/bundle' }, destination: { serverId: 'srv-b', path: '/dst-bundle' }, }, { id: 'xfer-direct', type: 'transfer', dependsOn: ['gen-token'], mode: 'direct', source: { serverId: 'srv-a', path: '/single.txt' }, destination: { serverId: 'srv-b', path: '/direct-copy.txt' }, }, { id: 'will-fail', type: 'exec', dependsOn: ['gen-token'], target: { serverId: 'srv-b' }, command: 'echo FAIL_NOW', onFailure: 'continue', }, { id: 'on-fail-branch', type: 'exec', dependsOn: [{ stepId: 'will-fail', on: 'failure' }], target: { serverId: 'srv-a' }, command: ': PRINT_CAP; printf "CAP=%s|STEP=%s" {{captures.tok}} {{steps.gen-token.stdout}}', }, { id: 'on-always-cleanup', type: 'exec', dependsOn: [ { stepId: 'on-fail-branch', on: 'always' }, { stepId: 'xfer-dir', on: 'success' }, ], target: { serverId: 'srv-b' }, command: 'echo cleanup-done', }, ], }; expect( (await api('/api/workflows', { method: 'POST', body: dagWf })).status, ).toBe(201); const pinnedRes = await api('/api/workflows?pinnedOnly=1'); expect(pinnedRes.status).toBe(200); expect( (pinnedRes.data.workflows as Array<{ workflow: { id: string } }>).map( (w) => w.workflow.id, ), ).toEqual(['wf-dag-full']); // Dry-run works even under Safe Mode const dryRes = await api('/api/workflows/wf-dag-full/dry-run', { method: 'POST', safeMode: true, body: { inputs: { tag: 'v42' } }, }); expect(dryRes.status).toBe(200); const plan = dryRes.data.plan as { steps: Array<{ stepId: string; wave: number; renderedCommand?: string; renderedPath?: string; }>; }; const tailPlan = plan.steps.find((s) => s.stepId === 'tail-log'); expect(tailPlan?.renderedPath).toBe('/logs/app.log'); const genPlan = plan.steps.find((s) => s.stepId === 'gen-token'); expect(genPlan?.renderedCommand).toContain("'v42'"); const dagStart = await api('/api/workflows/wf-dag-full/run', { method: 'POST', body: { inputs: { tag: 'v42' } }, }); expect(dagStart.status).toBe(202); const dagRunId = String(dagStart.data.runId); const dagDetail = await waitForWorkflowRun(server, dagRunId, 10_000); expect(dagDetail.run.status).toBe('succeeded'); const logByStep = new Map(dagDetail.stepLogs.map((l) => [l.stepId, l])); expect(logByStep.get('gen-token')?.stdout).toBe('tok-v42'); expect(logByStep.get('tail-log')?.stdout.trim()).toBe('l3\nl4'); expect(logByStep.get('svc-restart')?.stdout).toContain('restarted nginx on A'); expect(logByStep.get('will-fail')?.exitCode).toBe(42); expect(logByStep.get('on-fail-branch')?.stdout).toBe('CAP=tok-v42|STEP=tok-v42'); expect(logByStep.get('on-always-cleanup')?.exitCode).toBe(0); // Verify hub-relayed SFTP transfer files landed on srvB without touching local disk expect(fs.readFileSync(path.join(sftpRootB, 'dst-single.txt'), 'utf8')).toBe( 'single-file-payload\n', ); expect(fs.readFileSync(path.join(sftpRootB, 'dst-bundle', 'top.txt'), 'utf8')).toBe( 'top-content', ); expect( fs.readFileSync(path.join(sftpRootB, 'dst-bundle', 'nested', 'deep.txt'), 'utf8'), ).toBe('deep-content'); expect(directRsyncCmds.some((c) => c.includes(`ops@127.0.0.1:/direct-copy.txt`))).toBe( true, ); // Verify WS workflow:run + stream:wf: replay frames ws.send(JSON.stringify({ type: 'sub', channels: [`stream:wf:${dagRunId}`] })); await waitFor(() => frames.some((f) => { if (f.type !== 'stream:chunk' || f.jobId !== `wf:${dagRunId}` || f.stream !== 'meta') { return false; } try { return (JSON.parse(String(f.data)) as { event?: string }).event === 'done'; } catch { return false; } }), ); // --- 4. Overlap Policies ('skip', 'queue', 'cancel-previous'), Timeout & Manual Cancel --- await api('/api/workflows', { method: 'POST', body: { id: 'wf-overlap-skip', name: 'Overlap Skip', enabled: true, trigger: { type: 'manual' }, overlapPolicy: 'skip', display: { mode: 'log' }, inputs: [], steps: [{ id: 's1', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_250__' }], }, }); const rSkip1 = await api('/api/workflows/wf-overlap-skip/run', { method: 'POST', body: {} }); expect(rSkip1.status).toBe(202); const rSkip2 = await api('/api/workflows/wf-overlap-skip/run', { method: 'POST', body: {} }); expect(rSkip2.status).toBe(200); expect(rSkip2.data.status).toBe('skipped'); expect((await waitForWorkflowRun(server, String(rSkip1.data.runId))).run.status).toBe('succeeded'); await api('/api/workflows', { method: 'POST', body: { id: 'wf-overlap-queue', name: 'Overlap Queue', enabled: true, trigger: { type: 'manual' }, overlapPolicy: 'queue', display: { mode: 'log' }, inputs: [], steps: [{ id: 's1', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_250__' }], }, }); const rQ1 = await api('/api/workflows/wf-overlap-queue/run', { method: 'POST', body: {} }); const rQ2 = await api('/api/workflows/wf-overlap-queue/run', { method: 'POST', body: {} }); expect(rQ1.status).toBe(202); expect(rQ2.status).toBe(202); expect(rQ2.data.status).toBe('queued'); expect((await waitForWorkflowRun(server, String(rQ1.data.runId))).run.status).toBe('succeeded'); expect((await waitForWorkflowRun(server, String(rQ2.data.runId))).run.status).toBe('succeeded'); await api('/api/workflows', { method: 'POST', body: { id: 'wf-overlap-cancel', name: 'Overlap Cancel Prev', enabled: true, trigger: { type: 'manual' }, overlapPolicy: 'cancel-previous', display: { mode: 'log' }, inputs: [], steps: [{ id: 's1', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_250__' }], }, }); const rC1 = await api('/api/workflows/wf-overlap-cancel/run', { method: 'POST', body: {} }); const rC2 = await api('/api/workflows/wf-overlap-cancel/run', { method: 'POST', body: {} }); expect(rC2.status).toBe(202); expect((await waitForWorkflowRun(server, String(rC1.data.runId))).run.status).toBe('cancelled'); expect((await waitForWorkflowRun(server, String(rC2.data.runId))).run.status).toBe('succeeded'); // Step timeoutSec: 1 + manual run cancel await api('/api/workflows', { method: 'POST', body: { id: 'wf-timeout', name: 'Timeout Test', enabled: true, trigger: { type: 'manual' }, overlapPolicy: 'skip', display: { mode: 'log' }, inputs: [], steps: [ { id: 'slow', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_2S__', timeoutSec: 1, }, ], }, }); const rTimeout = await api('/api/workflows/wf-timeout/run', { method: 'POST', body: {} }); const dTimeout = await waitForWorkflowRun(server, String(rTimeout.data.runId)); expect(dTimeout.run.status).toBe('failed'); expect(dTimeout.stepLogs[0]?.stderr).toMatch(/timed out/i); const rToCancel = await api('/api/workflows', { method: 'POST', body: { id: 'wf-manual-cancel', name: 'Manual Cancel', enabled: true, trigger: { type: 'manual' }, overlapPolicy: 'skip', display: { mode: 'log' }, inputs: [], steps: [{ id: 'slow', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_2S__' }], }, }); expect(rToCancel.status).toBe(201); const rManStart = await api('/api/workflows/wf-manual-cancel/run', { method: 'POST', body: {} }); const manCancelRes = await api(`/api/workflows/runs/${String(rManStart.data.runId)}/cancel`, { method: 'POST', }); expect(manCancelRes.data.cancelled).toBe(true); const dCancelled = await waitForWorkflowRun(server, String(rManStart.data.runId)); expect(dCancelled.run.status).toBe('cancelled'); expect(dCancelled.run.cancelledBy).toBe('admin'); // --- 5. Cron Workflow Scheduling (5-field enforced; 6-field rejected) --- const badCronRes = await api('/api/workflows', { method: 'POST', body: { id: 'wf-cron-bad', name: '6-Field Spam Cron', enabled: true, trigger: { type: 'cron', expression: '* * * * * *', timezone: 'UTC' }, overlapPolicy: 'skip', display: { mode: 'log' }, inputs: [], steps: [{ id: 'tick', type: 'exec', target: { serverId: 'srv-b' }, command: 'echo NOPE' }], }, }); expect(badCronRes.status).toBe(400); const okCronRes = await api('/api/workflows', { method: 'POST', body: { id: 'wf-cron-sec', name: 'Every Minute Cron', enabled: true, trigger: { type: 'cron', expression: '* * * * *', timezone: 'UTC' }, overlapPolicy: 'skip', display: { mode: 'log' }, inputs: [], steps: [{ id: 'tick', type: 'exec', target: { serverId: 'srv-b' }, command: 'echo CRON_TICK' }], }, }); expect(okCronRes.status).toBe(201); const listSummary = await api('/api/workflows'); const cronSummary = ( listSummary.data.workflows as Array<{ workflow: { id: string }; nextRunAt: number | null; }> ).find((w) => w.workflow.id === 'wf-cron-sec'); expect(typeof cronSummary?.nextRunAt).toBe('number'); expect(cronSummary!.nextRunAt!).toBeGreaterThan(Date.now() - 2000); expect(await server.workflowEngine.triggerScheduledCron('wf-cron-sec')).toBe(true); const cronRun = await waitFor( () => { const runs = server.workflowEngine.listRuns('wf-cron-sec'); return runs.find((r) => r.triggerSource === 'cron' && r.status === 'succeeded'); }, 5000, ); expect(cronRun.triggerSource).toBe('cron'); await api('/api/workflows/wf-cron-sec', { method: 'DELETE' }); }, ); });