verify-opencode-host-smoke.ts 8.8 KB

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