Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Preserve bounded Windows test diagnostics after launcher interruption (#11572)

[._.]/db3ea09ffa5e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8dc76800bd..1229d96446 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -854,6 +854,8 @@ jobs:
# (#10415). Observed healthy runs take 2-10 minutes.
timeout-minutes: 15
env:
+ # Outside the launcher's disposable temp root; recoverable after exit.
+ PORTOS_CI_DIAGNOSTICS_DIR: ${{ runner.temp }}/portos-ci-diagnostics
CI_TEST_MODE: ${{ needs.impact.outputs.windows_mode }}
CI_TEST_FILES: ${{ needs.impact.outputs.windows_files }}
CI_TEST_SOURCES: ${{ needs.impact.outputs.windows_sources }}
@@ -865,6 +867,14 @@ jobs:
PORTOS_CI_MAX_WORKERS: 2
run: node scripts/run-ci-tests.js server
+ - name: Preserve Windows test failure diagnostics
+ if: failure()
+ continue-on-error: true
+ timeout-minutes: 1
+ env:
+ PORTOS_CI_DIAGNOSTICS_DIR: ${{ runner.temp }}/portos-ci-diagnostics
+ run: node scripts/ci-test-diagnostics.js
+
- name: Report the failure, then cancel sibling CI jobs
if: failure() && github.event_name == 'pull_request'
env:
diff --git a/scripts/ci-test-diagnostics.js b/scripts/ci-test-diagnostics.js
new file mode 100644
index 0000000000..2083177cd7
--- /dev/null
+++ b/scripts/ci-test-diagnostics.js
@@ -0,0 +1,104 @@
+import { readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
+import { basename, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { reportWindowsCrashDiagnostics } from './ci-windows-crash-diagnostics.js';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
+import { writeStepSummary } from './lib/githubOutput.js';
+
+const repoRoot = fileURLToPath(new URL('../', import.meta.url)).replace(/\\/g, '/');
+
+// Publish repository identities only; never expose a runner's private paths.
+export function diagnosticTestFile(value) {
+ const normalized = String(value ?? '').replace(/\\/g, '/');
+ if (normalized.length > 1000) return '<unavailable>';
+ const path = normalized.startsWith(repoRoot) ? normalized.slice(repoRoot.length) : normalized.replace(/^\.\.?\//, '');
+ if (path.length <= 240 && /^(?:server|client|scripts|lib|autofixer)\/(?:[\w.-]+\/)*[\w.-]+$/.test(path)
+ && !path.split('/').includes('..')) return path;
+ const name = basename(normalized);
+ return /^[\w.-]+\.test\.[\w]+$/.test(name) ? `<outside-repository>/${name}` : '<unavailable>';
+}
+
+export function persistTestDiagnostic(path, value) {
+ try {
+ writeFileSync(`${path}.tmp`, JSON.stringify(value));
+ renameSync(`${path}.tmp`, path);
+ } catch {
+ console.error('Unable to persist CI test diagnostics.');
+ }
+}
+
+function readReport(path, limit = 100_000) {
+ if (statSync(path).size > limit) throw new Error('report exceeds limit');
+ return JSON.parse(readFileSync(path, 'utf8'));
+}
+
+// Independent of the launcher's close callback. Only bounded projections reach
+// logs/summary: raw reports, error messages and environment values stay private.
+export async function collectTestDiagnostics(root, {
+ diagnose = reportWindowsCrashDiagnostics, logger = console, writeSummary = writeStepSummary,
+} = {}) {
+ const lines = [];
+ let startedAt;
+ let attempts = [];
+ try {
+ attempts = readdirSync(root).filter(name => /^portos-vitest-[\w-]+$/.test(name));
+ const start = name => {
+ try { return Number(readReport(join(root, name, 'invocation.json')).startedAt) || 0; }
+ catch { return 0; }
+ };
+ attempts.sort((a, b) => start(a) - start(b));
+ if (attempts.length > 2) lines.push('Diagnostic gap: more than two invocations; collecting only the last two.');
+ } catch {
+ lines.push('Diagnostic gap: invocation directory unavailable.');
+ }
+ if (!attempts.length) lines.push('Inconclusive failure: no persisted test invocation; launcher completion is unverified.');
+ for (const [index, name] of attempts.slice(-2).entries()) {
+ const dir = join(root, name);
+ lines.push(`CI test invocation ${index + 1}:`);
+ try {
+ const invocation = readReport(join(dir, 'invocation.json'));
+ if (!Number.isFinite(invocation.startedAt) || typeof invocation.completed !== 'boolean') throw Error('invalid invocation');
+ startedAt = Math.min(startedAt ?? invocation.startedAt, invocation.startedAt);
+ lines.push(`Launcher ${invocation.completed ? 'completed' : 'interrupted or completion not recorded'}; `
+ + `exit=${Number.isInteger(invocation.status) ? invocation.status : 'unavailable'}; `
+ + `signal=${/^SIG[A-Z]+$/.test(invocation.signal) ? invocation.signal : 'none'}.`);
+ if (Array.isArray(invocation.selectors)) lines.push(`Selected inputs (up to 100): ${invocation.selectors.slice(0, 100).map(diagnosticTestFile).join(', ') || 'full suite or no file selectors'}`);
+ } catch {
+ lines.push('Diagnostic gap: invocation metadata unavailable; launcher completion is unverified.');
+ }
+ try {
+ const run = readReport(join(dir, 'run.json'), 160_000);
+ if (!Array.isArray(run.activeModules) || !Array.isArray(run.completedModules)
+ || !Number.isInteger(run.completedCount) || !Number.isInteger(run.errorCount)) throw Error('invalid progress');
+ const reason = ['passed', 'failed', 'interrupted', 'not-finished'].includes(run.reason) ? run.reason : 'unavailable';
+ lines.push(`Vitest progress: reason=${reason}; completed=${run.completedCount}; unhandledErrors=${run.errorCount}.`);
+ lines.push(`Queued/unfinished modules (up to 100): ${run.activeModules.slice(0, 100).map(diagnosticTestFile).join(', ') || 'none recorded'}`);
+ lines.push(`Last completed modules (up to 100): ${run.completedModules.slice(-100).map(diagnosticTestFile).join(', ') || 'none recorded'}`);
+ } catch {
+ lines.push('Diagnostic gap: Vitest progress unavailable; active test file is unknown.');
+ }
+ try {
+ const report = readReport(join(dir, 'failures.json'), 32 * 1024 * 1024);
+ if (!Array.isArray(report.testResults)) throw Error('invalid failures');
+ const failed = report.testResults.filter(suite => suite.status === 'failed');
+ lines.push(failed.length
+ ? `Failed suites (up to 10): ${failed.slice(0, 10).map(suite => diagnosticTestFile(suite.name)).join(', ')}`
+ : 'Inconclusive failure: structured report contains no failed suite.');
+ } catch {
+ lines.push('Inconclusive failure: structured test report missing, malformed, or oversized.');
+ }
+ }
+ for (const line of lines) logger.warn(line);
+ try { writeSummary(lines.join('\n\n')); }
+ catch { logger.warn('CI test diagnostic summary unavailable; see the job log.'); }
+ // Without invocation metadata, explicitly use the step's 15-minute budget.
+ if (startedAt === undefined) logger.warn('Windows event query uses a fallback 15-minute window; invocation start is unknown.');
+ try { await diagnose(startedAt ?? Date.now() - 15 * 60_000); }
+ catch { logger.warn('Windows native crash diagnostics unavailable.'); }
+ return lines;
+}
+
+if (isDirectlyInvoked(import.meta.url)) {
+ try { await collectTestDiagnostics(process.env.PORTOS_CI_DIAGNOSTICS_DIR); }
+ catch { console.error('CI test diagnostic collection unavailable; original test failure is unchanged.'); }
+}
diff --git a/scripts/ci-test-diagnostics.test.js b/scripts/ci-test-diagnostics.test.js
new file mode 100644
index 0000000000..2c483a26ae
--- /dev/null
+++ b/scripts/ci-test-diagnostics.test.js
@@ -0,0 +1,128 @@
+import { spawnSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { delimiter, join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { describe, expect, it, vi } from 'vitest';
+import { collectTestDiagnostics } from './ci-test-diagnostics.js';
+import { workflowJobs } from './lib/workflowJobs.js';
+
+const launcher = new URL('./run-ci-tests.js', import.meta.url).href;
+const reporter = new URL('./vitestRunDiagnostics.js', import.meta.url).href;
+
+function fixture(abrupt) {
+ const root = mkdtempSync(join(tmpdir(), 'ci-diagnostics-'));
+ const reports = join(root, 'reports');
+ mkdirSync(reports);
+ const npmScript = join(root, 'npm.mjs');
+ writeFileSync(npmScript, `
+ import reporter from ${JSON.stringify(reporter)};
+ import { writeFileSync } from 'node:fs';
+ if (process.env.PORTOS_CI_DIAGNOSTICS_DIR) throw Error('nested launcher inherited durable ownership');
+ const hooks = reporter();
+ hooks.onInit({ onClose() {} });
+ hooks.onTestModuleQueued?.({ moduleId: 'server/lib/synthetic.test.js' });
+ if (${abrupt}) {
+ // Only this fixture's known launcher PID; no process discovery or live jobs.
+ process.kill(Number(process.env.FIXTURE_LAUNCHER_PID), 'SIGKILL');
+ } else {
+ hooks.onTestModuleEnd?.({ moduleId: 'server/lib/synthetic.test.js' });
+ hooks.onTestRunEnd([], [], 'failed');
+ const output = process.argv.find(arg => arg.startsWith('--outputFile.json=')).split('=').slice(1).join('=');
+ writeFileSync(output, JSON.stringify({ testResults: [{
+ name: 'server/lib/synthetic.test.js', status: 'failed', assertionResults: [],
+ message: 'example-private-message C:/Users/example-private/secret',
+ }] }));
+ }
+ process.exitCode = 17;
+ `);
+ writeFileSync(join(root, 'npm'), `#!${process.execPath}\nimport(${JSON.stringify(pathToFileURL(npmScript).href)});`, { mode: 0o755 });
+ writeFileSync(join(root, 'npm.cmd'), `@"${process.execPath}" "${npmScript}" %*\r\n`);
+ return { root, reports };
+}
+
+async function launchAndCollect(abrupt) {
+ const { root, reports } = fixture(abrupt);
+ try {
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', `
+ import { runNpm } from ${JSON.stringify(launcher)};
+ process.env.FIXTURE_LAUNCHER_PID = String(process.pid);
+ process.exitCode = (await runNpm('server', 'test:ci', ['./lib/synthetic.test.js'])).status;
+ `], {
+ encoding: 'utf8', timeout: 15_000,
+ env: { ...process.env, PATH: `${root}${delimiter}${process.env.PATH}`,
+ TMPDIR: root, TMP: root, TEMP: root, NODE_DISABLE_COMPILE_CACHE: '1',
+ PORTOS_CI_DIAGNOSTICS_DIR: reports, GITHUB_STEP_SUMMARY: '', GITHUB_ENV: '' },
+ });
+ expect(result.error).toBeUndefined();
+ if (abrupt) expect(result.signal === 'SIGKILL' || result.status !== 0).toBe(true);
+ else expect(result.status, result.stderr).toBe(17);
+ const attempts = readdirSync(reports);
+ expect(attempts).toHaveLength(1);
+ const invocation = JSON.parse(readFileSync(join(reports, attempts[0], 'invocation.json'), 'utf8'));
+ expect(invocation.completed).toBe(!abrupt);
+ const options = { diagnose: vi.fn(), logger: { warn: vi.fn() }, writeSummary: vi.fn() };
+ await collectTestDiagnostics(reports, options);
+ const output = options.writeSummary.mock.calls[0][0];
+ expect(output).toContain('server/lib/synthetic.test.js');
+ expect(output).not.toMatch(/example-private|Users|secret/);
+ expect(options.diagnose).toHaveBeenCalledWith(invocation.startedAt);
+ return output;
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+}
+
+describe('independent CI test failure recovery (#11552)', () => {
+ it('recovers a failed launcher result after its normal report callback', async () => {
+ const output = await launchAndCollect(false);
+ expect(output).toContain('Launcher completed; exit=17');
+ expect(output).toContain('reason=failed; completed=1');
+ expect(output).toContain('Failed suites (up to 10): server/lib/synthetic.test.js');
+ });
+
+ it('recovers an unfinished module after abrupt launcher death without claiming a test failure cause', async () => {
+ const output = await launchAndCollect(true);
+ expect(output).toContain('Launcher interrupted or completion not recorded; exit=unavailable');
+ expect(output).toContain('reason=not-finished; completed=0');
+ expect(output).toContain('structured test report missing');
+ });
+
+ it('keeps unavailable and invalid reports inconclusive even when summary and native collection fail', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'ci-diagnostics-invalid-'));
+ try {
+ const attempt = join(root, 'portos-vitest-fixture');
+ mkdirSync(attempt);
+ writeFileSync(join(attempt, 'invocation.json'), '{');
+ writeFileSync(join(attempt, 'run.json'), JSON.stringify({ reason: 'passed', activeModules: [] }));
+ writeFileSync(join(attempt, 'failures.json'), '{}');
+ const logger = { warn: vi.fn() };
+ const lines = await collectTestDiagnostics(root, { logger,
+ diagnose: async () => { throw Error('example-private'); },
+ writeSummary: () => { throw Error('example-private'); },
+ });
+ expect(lines.join('\n')).toContain('launcher completion is unverified');
+ expect(lines.join('\n')).toContain('active test file is unknown');
+ expect(lines.join('\n')).toContain('Inconclusive failure');
+ expect(logger.warn.mock.calls.flat().join('\n')).not.toContain('example-private');
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+
+ it('collects after failure and before sibling cancellation with bounded, non-masking failure handling', () => {
+ const workflow = readFileSync(new URL('../.github/workflows/ci.yml', import.meta.url), 'utf8');
+ const windows = workflowJobs(workflow)['windows-server'];
+ expect(windows).toContain('PORTOS_CI_DIAGNOSTICS_DIR: ${{ runner.temp }}/portos-ci-diagnostics');
+ const start = windows.indexOf(' - name: Preserve Windows test failure diagnostics');
+ expect(start).toBeGreaterThan(windows.indexOf('run: node scripts/run-ci-tests.js server'));
+ const end = windows.indexOf(' - name: Report the failure, then cancel sibling CI jobs');
+ expect(end).toBeGreaterThan(start);
+ const step = windows.slice(start, end);
+ expect(step).toContain('if: failure()');
+ expect(step).toContain('continue-on-error: true');
+ expect(step).toContain('timeout-minutes: 1');
+ expect(step).toContain('run: node scripts/ci-test-diagnostics.js');
+ const testStep = windows.slice(windows.indexOf('- name: Run server tests on Windows'), start);
+ expect(testStep).not.toContain('continue-on-error');
+ expect(windows.slice(end)).toContain("if: failure() && github.event_name == 'pull_request'");
+ });
+});
diff --git a/scripts/run-ci-tests.js b/scripts/run-ci-tests.js
index bea35592fa..6a156f1310 100644
--- a/scripts/run-ci-tests.js
+++ b/scripts/run-ci-tests.js
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import { spawn } from 'child_process';
-import { mkdtempSync, readFileSync, statSync, rmSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, statSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { stripVTControlCharacters } from 'node:util';
import { dirname, join } from 'path';
@@ -11,6 +11,7 @@ import { isDirectlyInvoked } from './lib/directInvocation.js';
import { sweepStaleRunRoots, writeOwnerFile } from './lib/vitestStaleRunRoots.js';
import { writeStepEnv, writeStepSummary } from './lib/githubOutput.js';
import { reportWindowsCrashDiagnostics } from './ci-windows-crash-diagnostics.js';
+import { diagnosticTestFile, persistTestDiagnostic } from './ci-test-diagnostics.js';
const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
@@ -139,7 +140,7 @@ export function structuredFailureDiagnostics(reportPath, runReportPath) {
const lines = [];
if (runReportPath) {
try {
- if (statSync(runReportPath).size > 100_000) throw new Error('run report exceeds limit');
+ if (statSync(runReportPath).size > 160_000) throw new Error('run report exceeds limit');
const run = JSON.parse(readFileSync(runReportPath, 'utf8'));
if (!Array.isArray(run.errors) || !run.errors.every(error => typeof error === 'string')) {
throw new Error('invalid run report schema');
@@ -191,20 +192,35 @@ export function structuredFailureDiagnostics(reportPath, runReportPath) {
* @returns {Promise<{status: number, output: string, interrupted?: NodeJS.Signals, error?: Error}>}
*/
export async function runNpm(scope, script, extraArgs) {
- const hostRoot = tmpdir();
- sweepStaleRunRoots(hostRoot, { prefix: 'portos-vitest-' });
+ // Opt-in, job-owned storage survives an abruptly terminated launcher. Keep
+ // separate roots for the initial attempt and the existing single retry.
+ const durableRoot = process.env.PORTOS_CI_DIAGNOSTICS_DIR;
+ let hostRoot = tmpdir();
+ if (durableRoot) {
+ try { mkdirSync(durableRoot, { recursive: true }); hostRoot = durableRoot; }
+ catch { console.error('Durable CI test diagnostics unavailable; using temporary reports.'); }
+ }
+ const durable = hostRoot === durableRoot;
+ if (!durable) sweepStaleRunRoots(hostRoot, { prefix: 'portos-vitest-' });
const reportDir = mkdtempSync(join(hostRoot, 'portos-vitest-'));
const reportPath = join(reportDir, 'failures.json');
try {
writeOwnerFile(reportDir);
return await runNpmWithReport(scope, script, extraArgs, reportPath);
} finally {
- rmSync(reportDir, { recursive: true, force: true });
+ if (!durable) rmSync(reportDir, { recursive: true, force: true });
}
}
function runNpmWithReport(scope, script, extraArgs, reportPath) {
const runReportPath = join(dirname(reportPath), 'run.json');
+ const invocationPath = join(dirname(reportPath), 'invocation.json');
+ const invocation = {
+ startedAt: Date.now(), completed: false, scope, script,
+ selectors: extraArgs.filter(arg => !arg.startsWith('-')).slice(0, 100)
+ .map(arg => diagnosticTestFile(arg.startsWith('../') ? arg.slice(3) : `${scope}/${arg.replace(/^\.\//, '')}`)),
+ };
+ persistTestDiagnostic(invocationPath, invocation);
const args = ['run', script, '--prefix', scope];
args.push('--', ...extraArgs, '--reporter=json', `--outputFile.json=${reportPath}`,
`--reporter=${join(repoRoot, 'scripts', 'vitestRunDiagnostics.js')}`);
@@ -216,8 +232,12 @@ function runNpmWithReport(scope, script, extraArgs, reportPath) {
// npm is a launcher, not the entire test tree. Give this invocation its
// own POSIX group; Windows killProcessTree uses taskkill /T instead.
const processGroup = process.platform !== 'win32';
+ const childEnv = { ...process.env, PORTOS_CI_DIAGNOSTICS_PATH: runReportPath };
+ // Only the workflow launcher owns durable attempts. Nested launcher
+ // fixtures must not overwrite or add to the job's failure provenance.
+ delete childEnv.PORTOS_CI_DIAGNOSTICS_DIR;
const child = spawn(command, spawnArgs, {
- env: { ...process.env, PORTOS_CI_DIAGNOSTICS_PATH: runReportPath }, cwd: repoRoot, detached: processGroup,
+ env: childEnv, cwd: repoRoot, detached: processGroup,
});
let interrupted;
let escalation;
@@ -253,6 +273,7 @@ function runNpmWithReport(scope, script, extraArgs, reportPath) {
process.removeListener('SIGINT', onSigint);
process.removeListener('SIGTERM', onSigterm);
const status = interrupted ? (interrupted === 'SIGINT' ? 130 : 143) : code ?? 1;
+ persistTestDiagnostic(invocationPath, { ...invocation, completed: true, status, signal: signal ?? interrupted ?? null });
if (status !== 0) {
console.error(`Test launcher exited: code=${code}, signal=${signal ?? 'none'}${interrupted ? `, interrupted=${interrupted}` : ''}`);
console.error(structuredFailureDiagnostics(reportPath, runReportPath));
diff --git a/scripts/run-ci-tests.test.js b/scripts/run-ci-tests.test.js
index 1b772c7c4b..9f60d3e785 100644
--- a/scripts/run-ci-tests.test.js
+++ b/scripts/run-ci-tests.test.js
@@ -406,7 +406,9 @@ describe('structured failure diagnostics', () => {
FIXTURE_CONFIG);
const runnerUrl = new URL('./run-ci-tests.js', import.meta.url).href;
const args = ['--config', join(fixture, 'vitest.config.mjs'), '--root', fixture, './fixture.test.js'];
- const env = { ...process.env, NODE_ENV: 'test', TMPDIR: host, TMP: host, TEMP: host, NODE_DISABLE_COMPILE_CACHE: '1' };
+ const durable = join(fixture, 'durable');
+ const env = { ...process.env, NODE_ENV: 'test', TMPDIR: host, TMP: host, TEMP: host, NODE_DISABLE_COMPILE_CACHE: '1',
+ PORTOS_CI_DIAGNOSTICS_DIR: durable };
delete env.PORTOS_TEST_TEMP_ROOT;
const result = spawnSync(process.execPath, ['--input-type=module', '-e',
`import { runNpm } from ${JSON.stringify(runnerUrl)};
@@ -416,6 +418,14 @@ describe('structured failure diagnostics', () => {
expect(result.error).toBeUndefined();
expect(result.status).toBe(1);
expect(readdirSync(host)).toEqual([]);
+ const attempts = readdirSync(durable);
+ expect(attempts).toHaveLength(1);
+ const invocation = JSON.parse(readFileSync(join(durable, attempts[0], 'invocation.json'), 'utf8'));
+ expect(invocation).toMatchObject({ completed: true, status: 1 });
+ const progress = JSON.parse(readFileSync(join(durable, attempts[0], 'run.json'), 'utf8'));
+ // Vitest reports bail=1 as an interrupted run, even with a failed suite.
+ expect(progress).toMatchObject({ reason: 'interrupted', completedCount: 1, activeModules: [],
+ completedModules: ['<outside-repository>/fixture.test.js'] });
expect(result.stdout).toContain('Test Files');
expect(result.stdout).toContain('Tests');
expect(result.stderr).toContain('Failed Tests');
diff --git a/scripts/vitestRunDiagnostics.js b/scripts/vitestRunDiagnostics.js
index d3ea064698..4150d5bee1 100644
--- a/scripts/vitestRunDiagnostics.js
+++ b/scripts/vitestRunDiagnostics.js
@@ -1,4 +1,4 @@
-import { writeFileSync } from 'node:fs';
+import { diagnosticTestFile, persistTestDiagnostic } from './ci-test-diagnostics.js';
// The JSON reporter includes test failures, but drops run-level errors such as
// unhandled rejections and worker crashes. Keep those independently of stdout.
@@ -11,23 +11,35 @@ function errorDiagnostic(error, depth = 0) {
}
export default function vitestRunDiagnostics() {
- let diagnostics = { reason: 'not-finished', errorCount: 0, errors: [] };
+ let diagnostics = { reason: 'not-finished', errorCount: 0, errors: [], completedCount: 0 };
+ const activeModules = new Set();
+ const completedModules = [];
const persist = () => {
const path = process.env.PORTOS_CI_DIAGNOSTICS_PATH;
if (!path) return;
- try {
- writeFileSync(path, JSON.stringify({ ...diagnostics, exitCode: process.exitCode ?? null }));
- } catch {
- // Diagnostic I/O must never turn a passing test run into a failure.
- console.error('Unable to persist Vitest run diagnostics.');
- }
+ persistTestDiagnostic(path, { ...diagnostics, activeModules: [...activeModules].slice(0, 100),
+ completedModules, exitCode: process.exitCode ?? null });
};
return {
onInit(vitest) {
vitest.onClose(persist);
+ persist();
+ },
+ onTestModuleQueued(module) {
+ // Queued includes import/collection, before any test body can run.
+ activeModules.add(diagnosticTestFile(module.moduleId));
+ persist();
+ },
+ onTestModuleEnd(module) {
+ const file = diagnosticTestFile(module.moduleId);
+ activeModules.delete(file);
+ completedModules.push(file);
+ if (completedModules.length > 100) completedModules.shift();
+ diagnostics.completedCount += 1;
+ persist();
},
onTestRunEnd(_modules, errors, reason) {
- diagnostics = { reason, errorCount: errors.length, errors: errors.slice(0, 10).map(error => errorDiagnostic(error)) };
+ diagnostics = { ...diagnostics, reason, errorCount: errors.length, errors: errors.slice(0, 10).map(error => errorDiagnostic(error)) };
persist();
},
onProcessTimeout() {