verify-opencode-host-smoke.ts 9.2 KB

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