verify-opencode-host-smoke.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import { spawn, spawnSync } from 'node:child_process';
  2. import {
  3. copyFileSync,
  4. existsSync,
  5. mkdirSync,
  6. mkdtempSync,
  7. rmSync,
  8. writeFileSync,
  9. } from 'node:fs';
  10. import { createServer } from 'node:net';
  11. import { tmpdir } from 'node:os';
  12. import path from 'node:path';
  13. import { fileURLToPath } from 'node:url';
  14. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  15. const repoRoot = path.resolve(__dirname, '..');
  16. const distEntry = path.join(repoRoot, 'dist', 'index.js');
  17. const opencodeVersion = process.env.OPENCODE_SMOKE_VERSION?.trim() || 'latest';
  18. function fail(message: string): never {
  19. throw new Error(message);
  20. }
  21. function run(
  22. command: string,
  23. args: string[],
  24. options: { cwd?: string; env?: Record<string, string> } = {},
  25. ) {
  26. const result = spawnSync(command, args, {
  27. cwd: options.cwd ?? repoRoot,
  28. env: {
  29. ...process.env,
  30. ...options.env,
  31. },
  32. encoding: 'utf8',
  33. stdio: ['ignore', 'pipe', 'pipe'],
  34. });
  35. if (result.status !== 0) {
  36. const detail = [result.stdout, result.stderr].filter(Boolean).join('\n');
  37. fail(
  38. `Command failed: ${command} ${args.join(' ')}${detail ? `\n${detail}` : ''}`,
  39. );
  40. }
  41. return result.stdout.trim();
  42. }
  43. function parsePackJson(output: string) {
  44. // npm <=11 prints a JSON array; npm 12 prints an object keyed by package
  45. // name. Parse the whole output first, then fall back to slicing the first
  46. // JSON array (older npm could prefix warnings on stdout).
  47. const trimmed = output.trim();
  48. try {
  49. const parsed: unknown = JSON.parse(trimmed);
  50. if (Array.isArray(parsed)) {
  51. return parsed as Array<{ filename?: string }>;
  52. }
  53. if (parsed && typeof parsed === 'object') {
  54. const entries = Object.values(parsed);
  55. if (entries.length > 0) {
  56. return entries as Array<{ filename?: string }>;
  57. }
  58. }
  59. } catch {
  60. // fall through to the array-slice heuristic
  61. }
  62. const start = output.indexOf('[');
  63. const end = output.lastIndexOf(']');
  64. if (start === -1 || end === -1 || end < start) {
  65. fail(`Could not locate npm pack JSON output:\n${output}`);
  66. }
  67. return JSON.parse(output.slice(start, end + 1)) as Array<{
  68. filename?: string;
  69. }>;
  70. }
  71. function packArtifact() {
  72. const output = run('npm', ['pack', '--json', '--ignore-scripts']);
  73. const parsed = parsePackJson(output);
  74. const tarball = parsed[0]?.filename;
  75. if (!tarball) fail(`npm pack did not return a tarball filename:\n${output}`);
  76. return path.join(repoRoot, tarball);
  77. }
  78. async function getFreePort() {
  79. const server = createServer();
  80. return await new Promise<number>((resolve, reject) => {
  81. server.once('error', reject);
  82. server.listen(0, '127.0.0.1', () => {
  83. const address = server.address();
  84. if (!address || typeof address === 'string') {
  85. server.close();
  86. reject(new Error('Failed to allocate free port'));
  87. return;
  88. }
  89. const { port } = address;
  90. server.close((error) => {
  91. if (error) reject(error);
  92. else resolve(port);
  93. });
  94. });
  95. });
  96. }
  97. async function waitForHealth(url: string, timeoutMs: number) {
  98. const deadline = Date.now() + timeoutMs;
  99. let lastError = 'health check did not succeed';
  100. while (Date.now() < deadline) {
  101. try {
  102. const response = await fetch(url, {
  103. signal: AbortSignal.timeout(2_000),
  104. });
  105. if (response.ok) return;
  106. lastError = `health check returned ${response.status}`;
  107. } catch (error) {
  108. lastError = error instanceof Error ? error.message : String(error);
  109. }
  110. await new Promise((resolve) => setTimeout(resolve, 250));
  111. }
  112. fail(`OpenCode server did not become healthy: ${lastError}`);
  113. }
  114. function formatCapturedLogs(stdout: string, stderr: string): string {
  115. const combined = [stdout.trim(), stderr.trim()].filter(Boolean).join('\n');
  116. if (!combined) return 'No stdout/stderr captured.';
  117. const lines = combined.split(/\r?\n/);
  118. return lines.slice(-200).join('\n');
  119. }
  120. async function stopProcess(child: ReturnType<typeof spawn>) {
  121. if (child.exitCode !== null) return;
  122. child.kill('SIGTERM');
  123. const exited = await Promise.race([
  124. new Promise<boolean>((resolve) => child.once('exit', () => resolve(true))),
  125. new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 5000)),
  126. ]);
  127. if (!exited && child.exitCode === null) {
  128. child.kill('SIGKILL');
  129. await new Promise((resolve) => child.once('exit', resolve));
  130. }
  131. }
  132. function assertNoPluginLoadErrors(logs: string) {
  133. const badPatterns = [
  134. /failed to load plugin/i,
  135. /cannot find module/i,
  136. /error=.*failed to load plugin/i,
  137. ];
  138. const match = badPatterns.find((pattern) => pattern.test(logs));
  139. if (!match) return;
  140. const relevantLines = logs
  141. .split(/\r?\n/)
  142. .filter((line) =>
  143. /plugin|failed to load|cannot find module|error=/i.test(line),
  144. )
  145. .slice(-20)
  146. .join('\n');
  147. fail(
  148. `OpenCode logs contain plugin load errors:${relevantLines ? `\n${relevantLines}` : ''}`,
  149. );
  150. }
  151. function omitOpencodeEnv(env: NodeJS.ProcessEnv) {
  152. return Object.fromEntries(
  153. Object.entries(env).filter(([key]) => !key.startsWith('OPENCODE_')),
  154. );
  155. }
  156. async function verifyHostSmoke(tarballPath: string) {
  157. const tempRoot = mkdtempSync(path.join(tmpdir(), 'omos-opencode-smoke-'));
  158. const homeDir = path.join(tempRoot, 'home');
  159. const configDir = path.join(tempRoot, 'config');
  160. const cacheDir = path.join(tempRoot, 'cache');
  161. const dataDir = path.join(tempRoot, 'data');
  162. const hostDir = path.join(tempRoot, 'host');
  163. const workspaceDir = path.join(tempRoot, 'workspace');
  164. const tarballTarget = path.join(tempRoot, path.basename(tarballPath));
  165. const port = await getFreePort();
  166. const healthTimeoutMs = process.platform === 'darwin' ? 60_000 : 30_000;
  167. try {
  168. console.log('Packing plugin tarball into isolated test root...');
  169. copyFileSync(tarballPath, tarballTarget);
  170. for (const dir of [
  171. homeDir,
  172. configDir,
  173. cacheDir,
  174. dataDir,
  175. hostDir,
  176. workspaceDir,
  177. ]) {
  178. mkdirSync(dir, { recursive: true });
  179. }
  180. const pluginDir = path.join(configDir, 'plugins');
  181. mkdirSync(pluginDir, { recursive: true });
  182. writeFileSync(
  183. path.join(hostDir, 'package.json'),
  184. JSON.stringify(
  185. { name: 'verify-opencode-host-smoke', private: true },
  186. null,
  187. 2,
  188. ),
  189. );
  190. console.log(
  191. `Installing opencode-ai@${opencodeVersion} into isolated test root...`,
  192. );
  193. run('bun', ['add', `opencode-ai@${opencodeVersion}`], { cwd: hostDir });
  194. const opencodeBin = path.join(hostDir, 'node_modules', '.bin', 'opencode');
  195. if (!existsSync(opencodeBin)) {
  196. fail(`Expected opencode binary at ${opencodeBin}`);
  197. }
  198. writeFileSync(
  199. path.join(configDir, 'package.json'),
  200. JSON.stringify(
  201. {
  202. type: 'module',
  203. dependencies: {
  204. 'oh-my-opencode-slim': `file:${tarballTarget}`,
  205. },
  206. },
  207. null,
  208. 2,
  209. ),
  210. );
  211. writeFileSync(
  212. path.join(pluginDir, 'load-oh-my-opencode-slim.js'),
  213. "export { default } from 'oh-my-opencode-slim';\n",
  214. );
  215. const config = JSON.stringify({
  216. $schema: 'https://opencode.ai/config.json',
  217. autoupdate: false,
  218. share: 'disabled',
  219. snapshot: false,
  220. });
  221. const env = {
  222. HOME: homeDir,
  223. XDG_CONFIG_HOME: configDir,
  224. XDG_CACHE_HOME: cacheDir,
  225. XDG_DATA_HOME: dataDir,
  226. OPENCODE_TEST_HOME: homeDir,
  227. OPENCODE_CONFIG_DIR: configDir,
  228. OPENCODE_CONFIG_CONTENT: config,
  229. OPENCODE_DISABLE_AUTOUPDATE: 'true',
  230. OPENCODE_DISABLE_MODELS_FETCH: 'true',
  231. OPENCODE_DISABLE_DEFAULT_PLUGINS: 'true',
  232. };
  233. console.log('Starting opencode serve with packaged plugin...');
  234. const child = spawn(
  235. opencodeBin,
  236. [
  237. 'serve',
  238. '--print-logs',
  239. '--log-level',
  240. 'DEBUG',
  241. '--hostname',
  242. '127.0.0.1',
  243. '--port',
  244. String(port),
  245. ],
  246. {
  247. cwd: workspaceDir,
  248. env: {
  249. ...omitOpencodeEnv(process.env),
  250. ...env,
  251. },
  252. stdio: ['ignore', 'pipe', 'pipe'],
  253. },
  254. );
  255. let stdout = '';
  256. let stderr = '';
  257. child.stdout?.on('data', (chunk) => {
  258. stdout += String(chunk);
  259. });
  260. child.stderr?.on('data', (chunk) => {
  261. stderr += String(chunk);
  262. });
  263. const exitPromise = new Promise<never>((_, reject) => {
  264. child.once('exit', (code, signal) => {
  265. reject(
  266. new Error(
  267. `opencode serve exited before smoke test completed (code=${code}, signal=${signal})\n${stdout}\n${stderr}`,
  268. ),
  269. );
  270. });
  271. });
  272. try {
  273. await Promise.race([
  274. waitForHealth(
  275. `http://127.0.0.1:${port}/global/health`,
  276. healthTimeoutMs,
  277. ),
  278. exitPromise,
  279. ]);
  280. await new Promise((resolve) => setTimeout(resolve, 1500));
  281. assertNoPluginLoadErrors(`${stdout}\n${stderr}`);
  282. } catch (error) {
  283. const message = error instanceof Error ? error.message : String(error);
  284. fail(
  285. `${message}\nCaptured OpenCode logs:\n${formatCapturedLogs(stdout, stderr)}`,
  286. );
  287. } finally {
  288. // Always terminate the spawned server, including on the health-check
  289. // failure path where stopProcess would otherwise never be reached and
  290. // the child process would leak away after the temp dir is removed.
  291. await stopProcess(child);
  292. }
  293. } finally {
  294. rmSync(tempRoot, { recursive: true, force: true });
  295. }
  296. }
  297. function cleanupTarball(tarballPath: string) {
  298. rmSync(tarballPath, { force: true });
  299. }
  300. async function main() {
  301. if (!existsSync(distEntry)) {
  302. fail(
  303. 'dist/index.js is missing. Run `bun run build` before verify:host-smoke.',
  304. );
  305. }
  306. const tarballPath = packArtifact();
  307. try {
  308. await verifyHostSmoke(tarballPath);
  309. } finally {
  310. cleanupTarball(tarballPath);
  311. }
  312. console.log('OpenCode host smoke verification passed.');
  313. }
  314. await main();
  315. process.exit(0);