import { cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; import { basename, dirname, join, relative, resolve, sep } from 'node:path'; import { pathToFileURL } from 'node:url'; import { afterAll, describe, expect, it } from '@rstest/core'; import { cliPath, execFileAsync, packageRoot, runDirFor, runFailure, summaryPathFor, } from './test-cli-support'; const temporaryDirectories: string[] = []; afterAll(() => { for (const directory of temporaryDirectories) { rmSync(directory, { recursive: true, force: true }); } const fixtures = join(__dirname, 'fixtures'); for (const entry of readdirSync(fixtures, { withFileTypes: true })) { if (entry.isDirectory()) { rmSync(join(fixtures, entry.name, 'midscene_run'), { recursive: true, force: true, }); } } }); const jsonFilesBelow = (directory: string): string[] => { if (!existsSync(directory)) return []; const files: string[] = []; const visit = (current: string) => { for (const entry of readdirSync(current, { withFileTypes: true })) { const path = join(current, entry.name); if (entry.isDirectory()) visit(path); else if (entry.name.endsWith('.json')) files.push(path); } }; visit(directory); return files; }; const documentResultFiles = (runDir: string): string[] => jsonFilesBelow(runDir).filter((path) => basename(path) === 'document.json'); const attemptResultFiles = (runDir: string): string[] => jsonFilesBelow(runDir).filter( (path) => relative(runDir, path).split(sep).includes('documents') && basename(path) !== 'document.json', ); const temporaryRun = (prefix: string) => { const temporary = mkdtempSync(join(tmpdir(), prefix)); temporaryDirectories.push(temporary); return { resultDir: join(temporary, 'results'), executionLog: join(temporary, 'executed.log'), }; }; describe('midscene-test CLI', () => { it.each(['default', 'environment', 'absolute-environment'] as const)( 'prints paths from the unified %s root when launched outside the project', async (source) => { const root = mkdtempSync(join(tmpdir(), 'cli-unified-root-')); temporaryDirectories.push(root); const commonUrl = pathToFileURL( resolve(packageRoot, '../shared/dist/es/common.mjs'), ).href; writeFileSync( join(root, 'midscene.config.mjs'), ` import { getMidsceneRunSubDir } from ${JSON.stringify(commonUrl)}; export default { nodes: [{name:'noop',execute(){ getMidsceneRunSubDir('output'); }}], }; `, ); writeFileSync( join(root, 'case.yaml'), 'cases:\n - name: scope\n steps:\n - noop: {}\n', ); const env = { ...process.env }; env.MIDSCENE_RUN_DIR = undefined; if (source === 'environment') env.MIDSCENE_RUN_DIR = 'artifacts'; if (source === 'absolute-environment') env.MIDSCENE_RUN_DIR = join(root, 'artifacts'); const execution = await execFileAsync( process.execPath, [cliPath, '--config', join(root, 'midscene.config.mjs')], { cwd: packageRoot, env, }, ); const artifactRoot = join( root, source === 'default' ? 'midscene_run' : 'artifacts', ); const resultDir = join(artifactRoot, 'test-results'); const summaryPath = summaryPathFor(resultDir); const summary = JSON.parse(readFileSync(summaryPath, 'utf8')); const reportPath = resolve(dirname(summaryPath), summary.report); expect(summary.status).toBe('success'); expect(execution.stdout).toContain(`Summary: ${summaryPath}`); expect(execution.stdout).toContain(`Report: ${reportPath}`); expect(existsSync(join(artifactRoot, 'output'))).toBe(true); expect(existsSync(join(root, '.midscene'))).toBe(false); }, ); it.each(['default', 'verbose'])( 'reports concurrent files, scoped warnings and per-model usage through the %s CLI', async (reporter) => { const root = mkdtempSync(join(tmpdir(), 'cli-concurrent-reporting-')); temporaryDirectories.push(root); const resultDir = join(root, 'results'); const loggerUrl = pathToFileURL( resolve(packageRoot, '../shared/dist/lib/logger.js'), ).href; writeFileSync( join(root, 'midscene.config.mjs'), ` import { getDebug } from ${JSON.stringify(loggerUrl)}; let starts = 0; let release; const bothStarted = new Promise((resolve) => { release = resolve; }); export default { projects: [{ name: 'web', setup: { name: 'shared', setup() { return {}; } }, fileSetup: { name: 'isolated', setup({ file, onTeardown }) { getDebug('demo:setup', { console: true })('setup ' + file.sourcePath); onTeardown(() => getDebug('demo:cleanup', { console: true })('cleanup ' + file.sourcePath)); return { path: file.sourcePath }; } }, }], test: { maxConcurrentProjects: 1, maxConcurrentFiles: 2 }, nodes: [{ name: 'demo.concurrent', async execute(ctx) { const name = ctx.context.path === 'a.yaml' ? 'model-A' : 'model-B'; ctx.report.addTrace({ type: 'midscene-execution', executionId: ctx.context.path, metrics: { modelCallCount: 1, modelTimeMs: 10, promptTokens: 100, completionTokens: 20, cachedInputTokens: 80, totalTokens: 120, models: [{ modelName: name, callCount: 1, modelCallTimeMs: 10, promptTokens: 100, completionTokens: 20, cachedInputTokens: 80, totalTokens: 120 }], } }); if (++starts === 2) release(); await bothStarted; if (ctx.context.path === 'b.yaml') throw new Error('controlled file failure'); } }, { name: 'demo.noop', execute() {} }], }; `, ); for (const path of ['a.yaml', 'b.yaml']) writeFileSync( join(root, path), 'cases:\n - name: checkout\n steps:\n - demo.concurrent: {}\n - demo.noop: {}\n - demo.noop: {}\n', ); const execution = await runFailure([ '--config', join(root, 'midscene.config.mjs'), '--result-dir', resultDir, '--reporter', reporter, ]); expect(execution.code).toBe(1); expect(execution.stdout).toContain( 'Concurrency 1 projects · 2 files (global limits)', ); expect(execution.stdout.match(/└─ ✓ a.yaml \(1 cases\)/g)).toHaveLength( 1, ); expect( execution.stdout.match(/└─ × b.yaml \(1 cases \| 1 failed\)/g), ).toHaveLength(1); expect(execution.stdout).toContain('Test Files 1 failed | 1 passed (2)'); expect( execution.stdout.split('\n').filter((line) => line.trim() === 'web'), ).toHaveLength(2); expect(execution.stdout).not.toMatch(/[✓×] web \(2 files\)/); for (const path of ['a.yaml', 'b.yaml']) { expect(execution.stdout).toContain( `WARN [web] › ${path} › fileSetup · setup ${path}`, ); expect(execution.stdout).toContain( `WARN [web] › ${path} › teardown · cleanup ${path}`, ); if (reporter === 'verbose') expect(execution.stdout).toContain( `[web] [${path}] → step 1/3: demo.concurrent`, ); } expect(execution.stdout).toContain( 'model-A · 120 total · 100 input (80 cached) · 20 output', ); expect(execution.stdout).toContain( 'model-B · 120 total · 100 input (80 cached) · 20 output', ); expect(execution.stderr).toContain('controlled file failure'); if (reporter === 'default') { expect(execution.stderr).toMatch(/Step\s+1\/3 · demo\.concurrent/); expect(execution.stderr).toContain('b.yaml:4'); } expect(execution.stdout + execution.stderr).not.toContain('\u001b'); const summary = JSON.parse( readFileSync(summaryPathFor(resultDir), 'utf8'), ); expect(summary.metrics).toMatchObject({ modelCallCount: 2, totalTokens: 240, }); }, ); it('publishes actual model usage across hooks and failed Case attempts without calling a model', async () => { const root = mkdtempSync(join(tmpdir(), 'cli-model-usage-')); temporaryDirectories.push(root); const resultDir = join(root, 'results'); const loggerUrl = pathToFileURL( resolve(packageRoot, '../shared/dist/lib/logger.js'), ).href; writeFileSync( join(root, 'midscene.config.mjs'), ` import { getDebug } from ${JSON.stringify(loggerUrl)}; let calls = 0; export default { projects: [{ name: 'demo', retry: 1 }], nodes: [{ name: 'demo.usage', execute(ctx) { const executionId = 'recorded-' + (++calls); ctx.report.addTrace({ type: 'midscene-execution', executionId, metrics: { modelCallCount: 1, modelTimeMs: 10, promptTokens: 100, completionTokens: 20, cachedInputTokens: 80, totalTokens: 120, models: [{ modelName: 'actual-model', callCount: 1, modelCallTimeMs: 10, promptTokens: 100, completionTokens: 20, cachedInputTokens: 80, totalTokens: 120 }], } }); if (ctx.scope === 'case' && ctx.case.attemptIndex === 0) { getDebug('demo:retry', { console: true, warning: { kind: 'model-request-retry', modelName: 'actual-model', error: Object.assign(new Error('limited'), { status: 429 }), callId: executionId, attempt: 1, maxAttempts: 2, delayMs: 2000 } })('raw provider detail'); throw new Error('controlled Case retry'); } } }], }; `, ); writeFileSync( join(root, 'case.yaml'), 'beforeAll:\n - demo.usage: {}\ncases:\n - name: recovered Case\n steps:\n - demo.usage: {}\nafterAll:\n - demo.usage: {}\n', ); const execution = await execFileAsync( process.execPath, [ cliPath, '--config', join(root, 'midscene.config.mjs'), '--result-dir', resultDir, ], { cwd: packageRoot, env: { ...process.env, MIDSCENE_MODEL_NAME: 'configured-model', MIDSCENE_PLANNING_MODEL_NAME: '', MIDSCENE_INSIGHT_MODEL_NAME: '', }, }, ); expect(execution.stdout).toContain('Models (env) configured-model'); expect(execution.stdout).toContain( 'Models: actual-model · 480 total · 400 input (320 cached) · 80 output', ); expect(execution.stdout).toContain('model request retry 2/2'); expect(execution.stdout).not.toContain('raw provider detail'); expect(execution.stdout).not.toContain('\u001b'); const summary = JSON.parse(readFileSync(summaryPathFor(resultDir), 'utf8')); expect(summary.metrics).toMatchObject({ modelCallCount: 4, totalTokens: 480, models: [{ modelName: 'actual-model', callCount: 4, totalTokens: 480 }], }); expect(summary.summary.passedAfterRetry).toBe(1); }); it('prints concise source locations and resolved inputs for final failures', async () => { const root = mkdtempSync(join(tmpdir(), 'cli-failure-details-')); temporaryDirectories.push(root); const resultDir = join(root, 'results'); writeFileSync( join(root, 'midscene.config.mjs'), `export default { projects: [{ name: 'headphones', retry: 1 }], nodes: [{ name: 'demo.outcome', execute({ input }) { if (input.outcome === 'final-failure') throw new Error('Expected 36, received 24.'); } }], };\n`, ); writeFileSync( join(root, 'cases.yaml'), [ 'cases:', ' - name: Case A', ' steps:', ' - demo.outcome:', ' outcome: success', ' marker: unrelated input marker', ' # Distinguish two occurrences of the same Node.', ' - demo.outcome:', ' outcome: final-failure', ' caseLabel: Case A', ' password: private-secret', ' - demo.outcome:', ' outcome: success', ' marker: unexecuted input marker', '', ].join('\n'), ); const execution = await runFailure([ '--config', join(root, 'midscene.config.mjs'), '--result-dir', resultDir, ]); expect(execution.code).toBe(1); expect(execution.stderr).toContain('FAIL [headphones] Case A'); expect(execution.stderr).toContain('Step 2/3 · demo.outcome'); expect(execution.stderr).toContain('Location cases.yaml:8'); expect(execution.stderr).toContain('Attempt 2/2'); expect(execution.stderr).toContain('Error: Expected 36, received 24.'); expect(execution.stderr).toContain('Input outcome: final-failure'); expect(execution.stderr).toContain('caseLabel: Case A'); expect(execution.stderr).toContain('password: private-secret'); expect(execution.stderr).toMatch(/at midscene\.config\.mjs:4:\d+/); expect(execution.stderr).not.toMatch( /unrelated input marker|unexecuted input marker|node_modules|NodeExecutionError/, ); expect(execution.stderr).not.toContain('\u001b'); const summary = JSON.parse(readFileSync(summaryPathFor(resultDir), 'utf8')); const attempt = summary.projects[0].cases[0].attempts.at(-1); const saved = JSON.parse( readFileSync(join(runDirFor(resultDir), attempt.resultFile), 'utf8'), ); expect(saved.steps[1].meta.sourceLocation).toEqual({ line: 8, column: 9 }); expect(saved.steps).toHaveLength(2); }); it('defaults to concise Case results without losing structured steps', async () => { const projectRoot = join(__dirname, 'fixtures', 'test-project'); const { resultDir, executionLog } = temporaryRun('midscene-concise-e2e-'); const execution = await execFileAsync( process.execPath, [ cliPath, '--config', join(projectRoot, 'midscene.config.ts'), '--result-dir', resultDir, ], { cwd: packageRoot, env: { ...process.env, WORKFLOW_E2E_LOG: executionLog }, }, ); expect(execution.stdout).toContain('1 projects · 2 files · 3 cases'); expect(execution.stdout).toContain('RUN'); expect( execution.stdout.match(/^(?: {3}│ {2}| {6})[├└]─ ✓ /gm), ).toHaveLength(3); expect(execution.stdout.match(/^ web$/gm)).toHaveLength(2); expect(execution.stdout.match(/└─ ✓ flows\/first.yaml/g)).toHaveLength(1); expect(execution.stdout).toContain('└─ ✓ flows/nested/second.yml'); expect(execution.stdout.indexOf('first case')).toBeLessThan( execution.stdout.indexOf('second case'), ); expect(execution.stdout).toContain('Test Files 2 passed (2)'); expect(execution.stdout).toContain('Cases 3 passed (3)'); expect(execution.stdout).not.toContain('\u001b'); expect(execution.stdout).not.toContain('Final results'); expect(execution.stdout).not.toContain('→ step'); expect(execution.stdout).not.toContain('attempt 1/'); expect(execution.stdout).not.toContain('[document'); const summary = JSON.parse(readFileSync(summaryPathFor(resultDir), 'utf8')); const attemptPath = join( runDirFor(resultDir), summary.projects[0].cases[0].attempts[0].resultFile, ); expect(JSON.parse(readFileSync(attemptPath, 'utf8')).steps).toHaveLength(2); expect(summary.summary.passed).toBe(3); }); it.each(['report', 'teardown'])( 'keeps %s failures focused after an action recovers on retry', async (phase) => { const root = mkdtempSync(join(tmpdir(), 'cli-infrastructure-error-')); temporaryDirectories.push(root); const resultDir = join(root, 'results'); writeFileSync( join(root, 'midscene.config.mjs'), ` let attempts = 0; function failCleanup() { throw new Error('controlled cleanup failure'); } export default { projects: [{ name: 'demo', retry: 1 }], ${phase === 'report' ? "output: { reportDir: 'blocked-report-directory' }," : ''} nodes: [{ name: 'demo.retry', execute({ onTeardown }) { attempts += 1; if (attempts === 1) throw new Error('recovered action failure'); ${phase === 'teardown' ? 'onTeardown(failCleanup);' : ''} return { data: { marker: 'unrelated output marker' } }; }, }], }; `, ); writeFileSync( join(root, 'case.yaml'), ` cases: - name: recovered action steps: - demo.retry: marker: unrelated input marker `, ); if (phase === 'report') { writeFileSync( join(root, 'blocked-report-directory'), 'Block report creation.', ); } const failure = await runFailure([ '--config', join(root, 'midscene.config.mjs'), '--result-dir', resultDir, '--reporter', 'verbose', ]); expect(failure.code).toBe(1); expect(failure.stdout).toContain('✓ step 1/1: demo.retry'); expect(failure.stdout).toContain( phase === 'report' ? 'Cases 1 passed (1)' : 'Cases 1 failed | 0 passed (1)', ); expect(failure.stdout).toContain('Summary:'); expect(failure.stderr).not.toContain('recovered action failure'); expect(failure.stderr).not.toContain('unrelated input marker'); expect(failure.stderr).not.toContain('unrelated output marker'); expect(failure.stderr).not.toContain('result: {'); expect(failure.stderr.match(/^FAIL midscene-test:/gm)).toHaveLength(1); if (phase === 'report') { expect(failure.stderr).toContain('infrastructure:'); expect(failure.stderr).toContain('Failed to write-report'); expect(failure.stderr).toContain('EEXIST'); } else { expect(failure.stderr).toContain('controlled cleanup failure'); expect(failure.stderr.match(/at failCleanup/g)).toHaveLength(1); } }, ); it('publishes only the midscene-test bin', () => { const packageJson = JSON.parse( readFileSync(join(packageRoot, 'package.json'), 'utf8'), ); expect(packageJson.bin).toEqual({ 'midscene-test': './bin/midscene-test', }); expect(existsSync(join(packageRoot, 'bin', 'midscene-workflow'))).toBe( false, ); }); it('runs all workflow documents serially and writes native project results', async () => { const projectRoot = join(__dirname, 'fixtures', 'test-project'); const { resultDir, executionLog } = temporaryRun('midscene-test-e2e-'); const execution = await execFileAsync( process.execPath, [ cliPath, '--config', join(projectRoot, 'midscene.config.ts'), '--result-dir', resultDir, '--reporter', 'verbose', ], { cwd: packageRoot, env: { ...process.env, WORKFLOW_E2E_LOG: executionLog }, }, ); expect(execution.stdout).toContain( 'midscene-test: preflighted 1 projects, 2 documents, 3 cases, 0 collection errors', ); expect(execution.stdout).toContain('[document 1/2] flows/first.yaml'); expect(execution.stdout).toContain(' [case 1/2] first case'); expect(execution.stdout).toContain(' → step 1/2: test.record'); expect(execution.stdout).toMatch( / {6}✓ step 1\/2: test\.record \(\d+ ms\)/, ); expect(execution.stdout).toContain('Cases 3 passed (3)'); expect(readFileSync(executionLog, 'utf8').trim().split('\n')).toEqual([ 'first:one', 'first:two', 'second:one', 'nested:one', 'nested:two', ]); const runDir = runDirFor(resultDir); expect(attemptResultFiles(runDir)).toHaveLength(3); expect(documentResultFiles(runDir)).toHaveLength(2); expect(existsSync(summaryPathFor(resultDir))).toBe(true); expect(execution.stdout).toContain(`Summary: ${summaryPathFor(resultDir)}`); expect(existsSync(join(resultDir, 'project.json'))).toBe(false); expect(existsSync(join(resultDir, 'manifest.json'))).toBe(false); expect(existsSync(join(resultDir, 'rstest-tests'))).toBe(false); const projectResult = JSON.parse( readFileSync(summaryPathFor(resultDir), 'utf8'), ); const reportPath = resolve( join(summaryPathFor(resultDir), '..'), projectResult.report, ); expect(existsSync(reportPath)).toBe(true); expect(execution.stdout).toContain(`Report: ${reportPath}`); expect(projectResult).toMatchObject({ schemaVersion: 3, runId: basename(runDir), factsRoot: '.', status: 'success', exitCode: 0, summary: { total: 3, passed: 3, failed: 0, notRun: 0, passedAfterRetry: 0, finalPassRate: 1, firstPassRate: 1, collectionErrors: 0, documentFailures: 0, }, projects: [ { projectId: 'project-0', name: 'web', cases: [ { status: 'success', attempts: [{ attemptIndex: 0 }] }, { status: 'success', attempts: [{ attemptIndex: 0 }] }, { status: 'success', attempts: [{ attemptIndex: 0 }] }, ], }, ], }); }); it('describes registered nodes without reading workflows or running setup', async () => { const projectRoot = mkdtempSync(join(packageRoot, '.node-spec-e2e-')); temporaryDirectories.push(projectRoot); cpSync(join(__dirname, 'fixtures', 'node-spec-project'), projectRoot, { recursive: true, }); const execution = await execFileAsync( process.execPath, [cliPath, 'nodes', projectRoot], { cwd: packageRoot, // Avoid Nx's conflicting color flags in this exact-output assertion. env: { ...process.env, FORCE_COLOR: undefined, NO_COLOR: '1' }, }, ); expect(execution.stderr).toBe(''); const specPath = join(projectRoot, 'midscene-node-spec.md'); expect(execution.stdout).toBe( `Registered Nodes (1):\n- order.create: Create an order in the test environment.\n\nNode Spec generated: ${specPath}\n`, ); const markdown = readFileSync(specPath, 'utf8'); expect(markdown).toContain('