|
| 1 | +import fs from "node:fs"; |
| 2 | +import path from "node:path"; |
| 3 | +import { setTimeout as delay } from "node:timers/promises"; |
| 4 | +import { afterEach, expect, it, vi } from "vitest"; |
| 5 | +import { |
| 6 | + resolveVitestCliEntry, |
| 7 | + resolveVitestNodeArgs, |
| 8 | + resolveVitestSpawnParams, |
| 9 | + spawnWatchedVitestProcess, |
| 10 | +} from "../../scripts/run-vitest.mts"; |
| 11 | +import { forceKillVitestProcessGroup } from "../../scripts/vitest-process-group.mts"; |
| 12 | +import { isProcessAlive } from "../helpers/process-wait.js"; |
| 13 | +import { withTestTimeout } from "../helpers/promise.js"; |
| 14 | +import { useAutoCleanupTempDirTracker } from "../helpers/temp-dir.js"; |
| 15 | + |
| 16 | +const repoRoot = path.resolve(import.meta.dirname, "../.."); |
| 17 | +const tempDirs = useAutoCleanupTempDirTracker(afterEach); |
| 18 | +const posixIt = process.platform === "win32" ? it.skip : it; |
| 19 | +const ioTimeoutMs = 15_000; |
| 20 | +const silenceMs = 1_000; |
| 21 | + |
| 22 | +async function waitForRealIo(ready: () => boolean, description: string) { |
| 23 | + const deadline = Date.now() + ioTimeoutMs; |
| 24 | + while (!ready()) { |
| 25 | + if (Date.now() >= deadline) { |
| 26 | + throw new Error(`Timed out waiting for ${description}`); |
| 27 | + } |
| 28 | + await delay(5); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +posixIt.each([false, true])( |
| 33 | + "keeps real case progress alive across watchdog windows, then stall=%s", |
| 34 | + async (stall) => { |
| 35 | + const root = tempDirs.make("oc-vt-progress-"); |
| 36 | + fs.symlinkSync( |
| 37 | + path.join(repoRoot, "node_modules"), |
| 38 | + path.join(root, "node_modules"), |
| 39 | + "junction", |
| 40 | + ); |
| 41 | + const configPath = path.join(root, "vitest.config.mjs"); |
| 42 | + // Vitest can batch a case result until later task activity. A file boundary |
| 43 | + // explicitly flushes updates, so waiting for its case line cannot deadlock |
| 44 | + // against the next case's release barrier. |
| 45 | + for (let index = 0; index < 5; index++) { |
| 46 | + fs.writeFileSync( |
| 47 | + path.join(root, `progress-${index}.test.ts`), |
| 48 | + `import fs from "node:fs"; |
| 49 | +import { expect, it } from "vitest"; |
| 50 | +import { waitForFile } from ${JSON.stringify(path.join(repoRoot, "test/helpers/process-wait.ts"))}; |
| 51 | +const index = ${index}; |
| 52 | +it("real progress " + index, async () => { |
| 53 | + const ready = ${JSON.stringify(root)} + "/ready-" + index; |
| 54 | + fs.writeFileSync(ready + ".tmp", String(process.pid)); |
| 55 | + fs.renameSync(ready + ".tmp", ready); |
| 56 | + await waitForFile(${JSON.stringify(root)} + "/release-" + index, 15000); |
| 57 | + expect(index).toBeLessThan(5); |
| 58 | +}); |
| 59 | +`, |
| 60 | + ); |
| 61 | + } |
| 62 | + fs.writeFileSync( |
| 63 | + configPath, |
| 64 | + `import tooling from ${JSON.stringify(path.join(repoRoot, "test/vitest/vitest.tooling.config.ts"))}; |
| 65 | +import { BaseSequencer } from "vitest/node"; |
| 66 | +class OrderedFixtures extends BaseSequencer { |
| 67 | + async sort(files) { return [...files].sort((a, b) => a.moduleId.localeCompare(b.moduleId)); } |
| 68 | +} |
| 69 | +export default { |
| 70 | + ...tooling, |
| 71 | + root: ${JSON.stringify(root)}, |
| 72 | + cacheDir: ${JSON.stringify(path.join(root, ".vite"))}, |
| 73 | + test: { |
| 74 | + ...tooling.test, dir: ${JSON.stringify(root)}, include: ["progress-*.test.ts"], maxWorkers: 1, |
| 75 | + // Pure Vitest fixtures need no OpenClaw environment setup or shared-state runner. |
| 76 | + setupFiles: [], runner: undefined, |
| 77 | + sequence: { ...tooling.test.sequence, sequencer: OrderedFixtures }, |
| 78 | + }, |
| 79 | +}; |
| 80 | +`, |
| 81 | + ); |
| 82 | + const env = { ...process.env }; |
| 83 | + for (const key of Object.keys(env)) { |
| 84 | + if (key.startsWith("VITEST") || key.startsWith("OPENCLAW_")) { |
| 85 | + delete env[key]; |
| 86 | + } |
| 87 | + } |
| 88 | + Object.assign(env, { |
| 89 | + AI_AGENT: "vitest-progress-test", |
| 90 | + GITHUB_ACTIONS: "false", |
| 91 | + NO_COLOR: "1", |
| 92 | + FORCE_COLOR: "0", |
| 93 | + OPENCLAW_VITEST_FS_MODULE_CACHE_PATH: path.join(root, "module-cache"), |
| 94 | + OPENCLAW_VITEST_NO_OUTPUT_TIMEOUT_MS: String(silenceMs), |
| 95 | + OPENCLAW_VITEST_NO_OUTPUT_HEARTBEAT_MS: "400", |
| 96 | + }); |
| 97 | + |
| 98 | + // The watchdog captures timer functions during synchronous registration. |
| 99 | + // Uninstall immediately: transport, readiness, diagnostics and group joins |
| 100 | + // must use real timers, while the watchdog retains its own Sinon clock. |
| 101 | + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); |
| 102 | + const { clock } = setTimeout as typeof setTimeout & { clock: { tick(ms: number): void } }; |
| 103 | + const onNoOutputTimeout = vi.fn(); |
| 104 | + let watched: ReturnType<typeof spawnWatchedVitestProcess>; |
| 105 | + try { |
| 106 | + watched = spawnWatchedVitestProcess({ |
| 107 | + pnpmArgs: [ |
| 108 | + "exec", |
| 109 | + "node", |
| 110 | + ...resolveVitestNodeArgs(env), |
| 111 | + resolveVitestCliEntry(), |
| 112 | + "run", |
| 113 | + "--config", |
| 114 | + configPath, |
| 115 | + ], |
| 116 | + spawnParams: { cwd: repoRoot, ...resolveVitestSpawnParams(env) }, |
| 117 | + env, |
| 118 | + onNoOutputTimeout, |
| 119 | + }); |
| 120 | + } finally { |
| 121 | + vi.useRealTimers(); |
| 122 | + } |
| 123 | + let output = ""; |
| 124 | + watched.child.stdout!.on("data", (chunk: string) => { |
| 125 | + output += chunk; |
| 126 | + }); |
| 127 | + watched.child.stderr!.on("data", (chunk: string) => { |
| 128 | + output += chunk; |
| 129 | + }); |
| 130 | + const casePassed = (index: number) => |
| 131 | + output |
| 132 | + .split("\n") |
| 133 | + .some((line) => line.includes("✓") && line.includes(` > real progress ${index} `)); |
| 134 | + let workerPid: number | undefined; |
| 135 | + try { |
| 136 | + for (let index = 0; index < 4; index++) { |
| 137 | + const readyPath = path.join(root, `ready-${index}`); |
| 138 | + await waitForRealIo(() => fs.existsSync(readyPath), `case ${index} readiness\n${output}`); |
| 139 | + workerPid = Number(fs.readFileSync(readyPath, "utf8")); |
| 140 | + clock.tick(600); |
| 141 | + expect(onNoOutputTimeout, output).not.toHaveBeenCalled(); |
| 142 | + fs.writeFileSync(path.join(root, `release-${index}`), ""); |
| 143 | + // File barriers never enter the watched pipes. Only Vitest's completed |
| 144 | + // case output can reset the watchdog before the next 600ms advance. |
| 145 | + await waitForRealIo( |
| 146 | + () => casePassed(index), |
| 147 | + `Vitest completion for case ${index}\n${output}`, |
| 148 | + ); |
| 149 | + } |
| 150 | + await waitForRealIo(() => fs.existsSync(path.join(root, "ready-4")), "final case readiness"); |
| 151 | + expect(isProcessAlive(watched.child.pid!)).toBe(true); |
| 152 | + expect(onNoOutputTimeout).not.toHaveBeenCalled(); |
| 153 | + if (stall) { |
| 154 | + clock.tick(silenceMs - 1); |
| 155 | + expect(onNoOutputTimeout).not.toHaveBeenCalled(); |
| 156 | + clock.tick(1); |
| 157 | + expect(onNoOutputTimeout).toHaveBeenCalledOnce(); |
| 158 | + } else { |
| 159 | + fs.writeFileSync(path.join(root, "release-4"), ""); |
| 160 | + } |
| 161 | + const result = await watched.completion; |
| 162 | + // Vitest's logger handles SIGTERM and exits with 128 + 15, rather than |
| 163 | + // leaving Node to report a signal-only exit (as a bare silent child does). |
| 164 | + expect(result, output).toEqual({ code: stall ? 143 : 0, signal: null }); |
| 165 | + expect(casePassed(4)).toBe(!stall); |
| 166 | + expect(isProcessAlive(watched.child.pid!)).toBe(false); |
| 167 | + expect(isProcessAlive(workerPid!)).toBe(false); |
| 168 | + } finally { |
| 169 | + watched.teardown(); |
| 170 | + forceKillVitestProcessGroup(watched.child); |
| 171 | + await withTestTimeout(watched.completion, ioTimeoutMs, "owned Vitest group did not stop"); |
| 172 | + } |
| 173 | + }, |
| 174 | +); |
0 commit comments