verify-opencode-host-smoke.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. if (response.ok) return;
  85. lastError = `health check returned ${response.status}`;
  86. } catch (error) {
  87. lastError = error instanceof Error ? error.message : String(error);
  88. }
  89. await new Promise((resolve) => setTimeout(resolve, 250));
  90. }
  91. fail(`OpenCode server did not become healthy: ${lastError}`);
  92. }
  93. function formatCapturedLogs(stdout: string, stderr: string): string {
  94. const combined = [stdout.trim(), stderr.trim()].filter(Boolean).join('\n');
  95. if (!combined) return 'No stdout/stderr captured.';
  96. const lines = combined.split(/\r?\n/);
  97. return lines.slice(-200).join('\n');
  98. }
  99. async function stopProcess(child: ReturnType<typeof spawn>) {
  100. if (child.exitCode !== null) return;
  101. child.kill('SIGTERM');
  102. const exited = await Promise.race([
  103. new Promise<boolean>((resolve) => child.once('exit', () => resolve(true))),
  104. new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 5000)),
  105. ]);
  106. if (!exited && child.exitCode === null) {
  107. child.kill('SIGKILL');
  108. await new Promise((resolve) => child.once('exit', resolve));
  109. }
  110. }
  111. function assertNoPluginLoadErrors(logs: string) {
  112. const badPatterns = [
  113. /failed to load plugin/i,
  114. /cannot find module/i,
  115. /error=.*failed to load plugin/i,
  116. ];
  117. const match = badPatterns.find((pattern) => pattern.test(logs));
  118. if (!match) return;
  119. const relevantLines = logs
  120. .split(/\r?\n/)
  121. .filter((line) =>
  122. /plugin|failed to load|cannot find module|error=/i.test(line),
  123. )
  124. .slice(-20)
  125. .join('\n');
  126. fail(
  127. `OpenCode logs contain plugin load errors:${relevantLines ? `\n${relevantLines}` : ''}`,
  128. );
  129. }
  130. async function verifyHostSmoke(tarballPath: string) {
  131. const tempRoot = mkdtempSync(path.join(tmpdir(), 'omos-opencode-smoke-'));
  132. const homeDir = path.join(tempRoot, 'home');
  133. const configDir = path.join(tempRoot, 'config');
  134. const cacheDir = path.join(tempRoot, 'cache');
  135. const dataDir = path.join(tempRoot, 'data');
  136. const hostDir = path.join(tempRoot, 'host');
  137. const workspaceDir = path.join(tempRoot, 'workspace');
  138. const tarballTarget = path.join(tempRoot, path.basename(tarballPath));
  139. const port = await getFreePort();
  140. const healthTimeoutMs = process.platform === 'darwin' ? 60_000 : 30_000;
  141. try {
  142. console.log('Packing plugin tarball into isolated test root...');
  143. copyFileSync(tarballPath, tarballTarget);
  144. for (const dir of [
  145. homeDir,
  146. configDir,
  147. cacheDir,
  148. dataDir,
  149. hostDir,
  150. workspaceDir,
  151. ]) {
  152. mkdirSync(dir, { recursive: true });
  153. }
  154. const pluginDir = path.join(configDir, 'plugins');
  155. mkdirSync(pluginDir, { recursive: true });
  156. writeFileSync(
  157. path.join(hostDir, 'package.json'),
  158. JSON.stringify(
  159. { name: 'verify-opencode-host-smoke', private: true },
  160. null,
  161. 2,
  162. ),
  163. );
  164. console.log('Installing opencode-ai into isolated test root...');
  165. run('bun', ['add', 'opencode-ai@latest'], { cwd: hostDir });
  166. const opencodeBin = path.join(hostDir, 'node_modules', '.bin', 'opencode');
  167. if (!existsSync(opencodeBin)) {
  168. fail(`Expected opencode binary at ${opencodeBin}`);
  169. }
  170. writeFileSync(
  171. path.join(configDir, 'package.json'),
  172. JSON.stringify(
  173. {
  174. type: 'module',
  175. dependencies: {
  176. 'oh-my-opencode-slim': `file:${tarballTarget}`,
  177. },
  178. },
  179. null,
  180. 2,
  181. ),
  182. );
  183. writeFileSync(
  184. path.join(pluginDir, 'load-oh-my-opencode-slim.js'),
  185. "export { default } from 'oh-my-opencode-slim';\n",
  186. );
  187. const config = JSON.stringify({
  188. $schema: 'https://opencode.ai/config.json',
  189. autoupdate: false,
  190. share: 'disabled',
  191. snapshot: false,
  192. });
  193. const env = {
  194. HOME: homeDir,
  195. XDG_CONFIG_HOME: configDir,
  196. XDG_CACHE_HOME: cacheDir,
  197. XDG_DATA_HOME: dataDir,
  198. OPENCODE_CONFIG_DIR: configDir,
  199. OPENCODE_CONFIG_CONTENT: config,
  200. OPENCODE_DISABLE_AUTOUPDATE: 'true',
  201. OPENCODE_DISABLE_MODELS_FETCH: 'true',
  202. OPENCODE_DISABLE_DEFAULT_PLUGINS: 'true',
  203. };
  204. console.log('Starting opencode serve with packaged plugin...');
  205. const child = spawn(
  206. opencodeBin,
  207. [
  208. 'serve',
  209. '--print-logs',
  210. '--log-level',
  211. 'DEBUG',
  212. '--hostname',
  213. '127.0.0.1',
  214. '--port',
  215. String(port),
  216. ],
  217. {
  218. cwd: workspaceDir,
  219. env: {
  220. ...process.env,
  221. ...env,
  222. },
  223. stdio: ['ignore', 'pipe', 'pipe'],
  224. },
  225. );
  226. let stdout = '';
  227. let stderr = '';
  228. child.stdout?.on('data', (chunk) => {
  229. stdout += String(chunk);
  230. });
  231. child.stderr?.on('data', (chunk) => {
  232. stderr += String(chunk);
  233. });
  234. const exitPromise = new Promise<never>((_, reject) => {
  235. child.once('exit', (code, signal) => {
  236. reject(
  237. new Error(
  238. `opencode serve exited before smoke test completed (code=${code}, signal=${signal})\n${stdout}\n${stderr}`,
  239. ),
  240. );
  241. });
  242. });
  243. try {
  244. await Promise.race([
  245. waitForHealth(`http://127.0.0.1:${port}/health`, healthTimeoutMs),
  246. exitPromise,
  247. ]);
  248. } catch (error) {
  249. const message = error instanceof Error ? error.message : String(error);
  250. fail(
  251. `${message}\nCaptured OpenCode logs:\n${formatCapturedLogs(stdout, stderr)}`,
  252. );
  253. }
  254. await new Promise((resolve) => setTimeout(resolve, 1500));
  255. assertNoPluginLoadErrors(`${stdout}\n${stderr}`);
  256. await stopProcess(child);
  257. } finally {
  258. rmSync(tempRoot, { recursive: true, force: true });
  259. }
  260. }
  261. function cleanupTarball(tarballPath: string) {
  262. rmSync(tarballPath, { force: true });
  263. }
  264. async function main() {
  265. if (!existsSync(distEntry)) {
  266. fail(
  267. 'dist/index.js is missing. Run `bun run build` before verify:host-smoke.',
  268. );
  269. }
  270. const tarballPath = packArtifact();
  271. try {
  272. await verifyHostSmoke(tarballPath);
  273. } finally {
  274. cleanupTarball(tarballPath);
  275. }
  276. console.log('OpenCode host smoke verification passed.');
  277. }
  278. await main();
  279. process.exit(0);