opencode.test.ts (19145B)
1 import { OpenCode } from "@opencode/sdk"; 2 3 import { describe, it, expect, beforeEach, afterEach } from "vitest"; 4 import * as path from "node:path"; 5 import * as os from "node:os"; 6 import { execFile } from "node:child_process"; 7 import { access, mkdtemp, rm } from "node:fs/promises"; 8 import { promisify } from "node:util"; 9 import openpod from "./index"; 10 11 const execFileAsync = promisify(execFile); 12 13 async function exists(target: string): Promise<boolean> { 14 try { 15 await access(target); 16 return true; 17 } catch { 18 return false; 19 } 20 } 21 22 // OpenCode SDK's close() shuts down its SQLite database before all pending 23 // fs callbacks drain from the event loop, causing an unhandled rejection 24 // ("database is not open") during vitest teardown. Suppress it. 25 process.on("unhandledRejection", (err) => { 26 if ((err as { code?: string })?.code === "ERR_INVALID_STATE") return; 27 throw err; 28 }); 29 30 describe("opencode", () => { 31 const openpodRoot = path.join(os.homedir(), ".local", "share", "openpod"); 32 33 let opencode: Awaited<ReturnType<typeof OpenCode.create>>; 34 35 async function cleanup(sessionId: string, dirs: string[]) { 36 try { 37 await execFileAsync("limactl", ["delete", "--force", sessionId]); 38 } catch { 39 // ignore 40 } 41 try { 42 await opencode.sessions.remove({ sessionID: sessionId }); 43 } catch { 44 // ignore 45 } 46 for (const d of dirs) { 47 try { 48 await rm(d, { recursive: true, force: true }); 49 } catch { 50 // ignore 51 } 52 } 53 } 54 55 beforeEach(async () => { 56 opencode = await OpenCode.create(); 57 await opencode.plugin(openpod); 58 }); 59 60 afterEach(async () => { 61 // `await using` registers opencode for disposal when this callback's scope 62 // ends, which calls opencode[Symbol.asyncDispose]() for us. It is a no-op 63 // if opencode is undefined (e.g. beforeEach failed before creating it). 64 await using _close = opencode; 65 }); 66 67 it("registers openpod plugin with opencode", async () => { 68 await opencode.sessions.create(); 69 70 let commands: Awaited<ReturnType<typeof opencode.command.list>> | undefined; 71 72 for (let i = 0; i < 20; i++) { 73 commands = await opencode.command.list(); 74 if ( 75 commands.data.some((c: { name: string }) => c.name === "clear-openpod") 76 ) 77 break; 78 await new Promise((r) => setTimeout(r, 50)); 79 } 80 81 expect( 82 commands!.data.some((c: { name: string }) => c.name === "clear-openpod"), 83 ).toBe(true); 84 }); 85 86 it("should not create openpod instance for uninitialized git repo", async () => { 87 // Create a temp directory that is not a git repo 88 const tempDir = await mkdtemp( 89 path.join(os.tmpdir(), "openpod-e2e-non-git-"), 90 ); 91 92 const session = await opencode.sessions.create(); 93 94 // Move the session to the non-git temp directory so the prompt hook 95 // fires in a non-git context 96 await opencode.sessions.move({ 97 sessionID: session.id, 98 directory: tempDir, 99 }); 100 101 // Wait for the move to take effect 102 await new Promise((r) => setTimeout(r, 200)); 103 104 // Trigger a prompt via the session API to fire the prompt hook. 105 await opencode.sessions.prompt({ 106 sessionID: session.id, 107 text: "hello", 108 }); 109 110 expect(await exists(path.join(openpodRoot, session.id))).toBe(false); 111 112 // Verify no lima instance was created for this session 113 const { stdout: listOutput } = await execFileAsync("limactl", ["list"]); 114 expect(listOutput).not.toContain(session.id); 115 116 // Clean up 117 await cleanup(session.id, [tempDir]); 118 }); 119 120 it("should not create openpod instance for uninitialized git origin", async () => { 121 // Create a temp directory and init a git repo (but no remote origin) 122 const tempDir = await mkdtemp( 123 path.join(os.tmpdir(), "openpod-e2e-no-origin-"), 124 ); 125 await execFileAsync("git", ["init"], { cwd: tempDir }); 126 127 const session = await opencode.sessions.create(); 128 129 await opencode.sessions.move({ 130 sessionID: session.id, 131 directory: tempDir, 132 }); 133 134 // Wait for the move to take effect 135 await new Promise((r) => setTimeout(r, 200)); 136 137 // Trigger a prompt via the session API to fire the prompt hook. 138 await opencode.sessions.prompt({ 139 sessionID: session.id, 140 text: "hello", 141 }); 142 143 expect(await exists(path.join(openpodRoot, session.id))).toBe(false); 144 145 // Verify no lima instance was created for this session 146 const { stdout: listOutput } = await execFileAsync("limactl", ["list"]); 147 expect(listOutput).not.toContain(session.id); 148 149 // Clean up 150 await cleanup(session.id, [tempDir]); 151 }); 152 153 it( 154 "should create openpod directory and lima instance for new session", 155 { timeout: 120_000 }, 156 async () => { 157 // Create a temp git repo with a remote origin 158 const tempDir = await mkdtemp( 159 path.join(os.tmpdir(), "openpod-e2e-happy-path-"), 160 ); 161 const bareDir = await mkdtemp( 162 path.join(os.tmpdir(), "openpod-bare-happy-path-"), 163 ); 164 await execFileAsync("git", ["init", "--bare"], { cwd: bareDir }); 165 await execFileAsync("git", ["init"], { cwd: tempDir }); 166 await execFileAsync("git", ["remote", "add", "origin", bareDir], { 167 cwd: tempDir, 168 }); 169 170 const session = await opencode.sessions.create(); 171 172 await opencode.sessions.move({ 173 sessionID: session.id, 174 directory: tempDir, 175 }); 176 177 // Wait for the move to take effect 178 await new Promise((r) => setTimeout(r, 200)); 179 180 // Trigger a prompt via the session API to fire the prompt hook. 181 await opencode.sessions.prompt({ 182 sessionID: session.id, 183 text: "hello", 184 }); 185 186 // Verify the openpod directory was created (cloned) 187 const sessionDir = path.join(openpodRoot, session.id); 188 expect(await exists(sessionDir)).toBe(true); 189 190 // Verify a lima instance was created for this session 191 const { stdout: listOutput } = await execFileAsync("limactl", ["list"]); 192 expect(listOutput).toContain(session.id); 193 194 // Clean up 195 await cleanup(session.id, [sessionDir, tempDir, bareDir]); 196 }, 197 ); 198 199 it( 200 "should recreate lima instance when re-prompted after it is deleted", 201 { timeout: 180_000 }, 202 async () => { 203 // Create a temp git repo with a remote origin 204 const tempDir = await mkdtemp( 205 path.join(os.tmpdir(), "openpod-e2e-recreate-"), 206 ); 207 const bareDir = await mkdtemp( 208 path.join(os.tmpdir(), "openpod-bare-recreate-"), 209 ); 210 await execFileAsync("git", ["init", "--bare"], { cwd: bareDir }); 211 await execFileAsync("git", ["init"], { cwd: tempDir }); 212 await execFileAsync("git", ["remote", "add", "origin", bareDir], { 213 cwd: tempDir, 214 }); 215 216 async function limaInstanceExists(name: string): Promise<boolean> { 217 try { 218 await execFileAsync("limactl", ["list", name]); 219 return true; 220 } catch { 221 return false; 222 } 223 } 224 225 async function limaInstanceStatus(name: string): Promise<string> { 226 try { 227 const { stdout } = await execFileAsync("limactl", [ 228 "list", 229 name, 230 "--format", 231 "{{.Status}}", 232 ]); 233 return stdout.trim(); 234 } catch { 235 return ""; 236 } 237 } 238 239 // The prompt hook creates and starts the lima instance synchronously, 240 // but poll anyway so a slow boot doesn't flake the assertion. 241 async function waitForRunningLima(name: string): Promise<string> { 242 let status = ""; 243 for (let i = 0; i < 120; i++) { 244 status = await limaInstanceStatus(name); 245 if (status === "Running") break; 246 await new Promise((r) => setTimeout(r, 250)); 247 } 248 return status; 249 } 250 251 const session = await opencode.sessions.create(); 252 const sessionDir = path.join(openpodRoot, session.id); 253 254 await opencode.sessions.move({ 255 sessionID: session.id, 256 directory: tempDir, 257 }); 258 259 // Wait for the move to take effect 260 await new Promise((r) => setTimeout(r, 200)); 261 262 // First prompt clones the project into the openpod directory and 263 // creates + starts the lima instance. 264 await opencode.sessions.prompt({ 265 sessionID: session.id, 266 text: "hello", 267 }); 268 269 // Verify the pod exists 270 expect(await exists(sessionDir)).toBe(true); 271 expect(await limaInstanceExists(session.id)).toBe(true); 272 expect(await waitForRunningLima(session.id)).toBe("Running"); 273 274 // Wait for the prompt hook's async session.move() to land the session 275 // in the openpod directory before re-prompting. 276 for (let i = 0; i < 50; i++) { 277 const current = await opencode.sessions.get({ sessionID: session.id }); 278 if (current.location?.directory === sessionDir) break; 279 await new Promise((r) => setTimeout(r, 100)); 280 } 281 282 // Delete the lima instance out from under the session, leaving the 283 // cloned pod directory in place. 284 await execFileAsync("limactl", ["delete", "--force", session.id]); 285 expect(await limaInstanceExists(session.id)).toBe(false); 286 287 // Re-prompt: the existing pod directory is reused and the lima 288 // instance is recreated. 289 await opencode.sessions.prompt({ 290 sessionID: session.id, 291 text: "hello again", 292 }); 293 294 // Verify the pod was restored 295 expect(await exists(sessionDir)).toBe(true); 296 expect(await limaInstanceExists(session.id)).toBe(true); 297 expect(await waitForRunningLima(session.id)).toBe("Running"); 298 299 // Clean up 300 await cleanup(session.id, [sessionDir, tempDir, bareDir]); 301 }, 302 ); 303 304 it( 305 "should remove lima instance and openpod directory when the session is deleted", 306 { timeout: 180_000 }, 307 async () => { 308 // Create a temp git repo with a remote origin 309 const tempDir = await mkdtemp( 310 path.join(os.tmpdir(), "openpod-e2e-delete-"), 311 ); 312 const bareDir = await mkdtemp( 313 path.join(os.tmpdir(), "openpod-bare-delete-"), 314 ); 315 await execFileAsync("git", ["init", "--bare"], { cwd: bareDir }); 316 await execFileAsync("git", ["init"], { cwd: tempDir }); 317 await execFileAsync("git", ["remote", "add", "origin", bareDir], { 318 cwd: tempDir, 319 }); 320 321 async function limaInstanceExists(name: string): Promise<boolean> { 322 try { 323 await execFileAsync("limactl", ["list", name]); 324 return true; 325 } catch { 326 return false; 327 } 328 } 329 330 const session = await opencode.sessions.create(); 331 const sessionDir = path.join(openpodRoot, session.id); 332 333 await opencode.sessions.move({ 334 sessionID: session.id, 335 directory: tempDir, 336 }); 337 338 // Wait for the move to take effect 339 await new Promise((r) => setTimeout(r, 200)); 340 341 // Prompt so the handler clones the project and creates the lima instance 342 await opencode.sessions.prompt({ 343 sessionID: session.id, 344 text: "hello", 345 }); 346 347 expect(await exists(sessionDir)).toBe(true); 348 expect(await limaInstanceExists(session.id)).toBe(true); 349 350 // Wait for the prompt hook's async session.move() to land the session 351 // in the openpod directory before deleting it. 352 for (let i = 0; i < 50; i++) { 353 const current = await opencode.sessions.get({ sessionID: session.id }); 354 if (current.location?.directory === sessionDir) break; 355 await new Promise((r) => setTimeout(r, 100)); 356 } 357 358 // Delete the session. The plugin's session.deleted handler should clean 359 // up the lima instance and the openpod directory. 360 await opencode.sessions.remove({ sessionID: session.id }); 361 362 // Poll for pod removal with independent waits that run concurrently. 363 async function waitForPodRemoval(): Promise<{ 364 limaRemoved: boolean; 365 dirRemoved: boolean; 366 }> { 367 async function waitFor( 368 condition: () => boolean | Promise<boolean>, 369 ): Promise<boolean> { 370 for (let i = 0; i < 100; i++) { 371 if (await condition()) return true; 372 await new Promise((r) => setTimeout(r, 100)); 373 } 374 return condition(); 375 } 376 377 const [limaRemoved, dirRemoved] = await Promise.all([ 378 waitFor(async () => !(await limaInstanceExists(session.id))), 379 waitFor(async () => !(await exists(sessionDir))), 380 ]); 381 return { limaRemoved, dirRemoved }; 382 } 383 384 const { limaRemoved, dirRemoved } = await waitForPodRemoval(); 385 expect(limaRemoved).toBe(true); 386 expect(dirRemoved).toBe(true); 387 388 // Clean up 389 await cleanup(session.id, [sessionDir, tempDir, bareDir]); 390 }, 391 ); 392 393 it( 394 "should remove directories, lima instances, and openpod sessions when clear-openpod runs", 395 { timeout: 180_000 }, 396 async () => { 397 // Create a temp git repo with a remote origin 398 const tempDir = await mkdtemp( 399 path.join(os.tmpdir(), "openpod-e2e-clear-"), 400 ); 401 const bareDir = await mkdtemp( 402 path.join(os.tmpdir(), "openpod-bare-clear-"), 403 ); 404 await execFileAsync("git", ["init", "--bare"], { cwd: bareDir }); 405 await execFileAsync("git", ["init"], { cwd: tempDir }); 406 await execFileAsync("git", ["remote", "add", "origin", bareDir], { 407 cwd: tempDir, 408 }); 409 410 async function limaInstanceExists(name: string): Promise<boolean> { 411 try { 412 await execFileAsync("limactl", ["list", name]); 413 return true; 414 } catch { 415 return false; 416 } 417 } 418 419 async function sessionExists(sessionID: string): Promise<boolean> { 420 try { 421 await opencode.sessions.get({ sessionID }); 422 return true; 423 } catch { 424 return false; 425 } 426 } 427 428 const session = await opencode.sessions.create(); 429 const sessionDir = path.join(openpodRoot, session.id); 430 431 await opencode.sessions.move({ 432 sessionID: session.id, 433 directory: tempDir, 434 }); 435 436 // Wait for the move to take effect 437 await new Promise((r) => setTimeout(r, 200)); 438 439 // Prompt so the handler clones the project and creates the lima instance 440 await opencode.sessions.prompt({ 441 sessionID: session.id, 442 text: "hello", 443 }); 444 445 expect(await exists(sessionDir)).toBe(true); 446 expect(await limaInstanceExists(session.id)).toBe(true); 447 448 // Wait for the prompt hook's async session.move() to land the session 449 // in the openpod directory before clearing it. 450 for (let i = 0; i < 50; i++) { 451 const current = await opencode.sessions.get({ sessionID: session.id }); 452 if (current.location?.directory === sessionDir) break; 453 await new Promise((r) => setTimeout(r, 100)); 454 } 455 456 // Run the clear-openpod command from the session. The command should 457 // stop and delete every lima instance, remove every openpod directory, 458 // and delete the openpod sessions. 459 await opencode.sessions.command({ 460 sessionID: session.id, 461 name: "clear-openpod", 462 text: "", 463 }); 464 465 // Poll for cleanup with independent waits that run concurrently. 466 async function waitForClear(): Promise<{ 467 limaRemoved: boolean; 468 dirRemoved: boolean; 469 sessionRemoved: boolean; 470 }> { 471 async function waitFor( 472 condition: () => boolean | Promise<boolean>, 473 ): Promise<boolean> { 474 for (let i = 0; i < 100; i++) { 475 if (await condition()) return true; 476 await new Promise((r) => setTimeout(r, 100)); 477 } 478 return condition(); 479 } 480 481 const [limaRemoved, dirRemoved, sessionRemoved] = await Promise.all([ 482 waitFor(async () => !(await limaInstanceExists(session.id))), 483 waitFor(async () => !(await exists(sessionDir))), 484 waitFor(async () => !(await sessionExists(session.id))), 485 ]); 486 return { limaRemoved, dirRemoved, sessionRemoved }; 487 } 488 489 const { limaRemoved, dirRemoved, sessionRemoved } = await waitForClear(); 490 expect(limaRemoved).toBe(true); 491 expect(dirRemoved).toBe(true); 492 expect(sessionRemoved).toBe(true); 493 494 // Clean up 495 await cleanup(session.id, [sessionDir, tempDir, bareDir]); 496 }, 497 ); 498 499 it( 500 "runs shell commands within the session lima instance", 501 { timeout: 120_000 }, 502 async () => { 503 // Create a temp git repo with a remote origin 504 const tempDir = await mkdtemp( 505 path.join(os.tmpdir(), "openpod-e2e-shell-"), 506 ); 507 const bareDir = await mkdtemp( 508 path.join(os.tmpdir(), "openpod-bare-shell-"), 509 ); 510 await execFileAsync("git", ["init", "--bare"], { cwd: bareDir }); 511 await execFileAsync("git", ["init"], { cwd: tempDir }); 512 await execFileAsync("git", ["remote", "add", "origin", bareDir], { 513 cwd: tempDir, 514 }); 515 516 const session = await opencode.sessions.create(); 517 518 await opencode.sessions.move({ 519 sessionID: session.id, 520 directory: tempDir, 521 }); 522 523 // Wait for the move to take effect 524 await new Promise((r) => setTimeout(r, 200)); 525 526 // Trigger a prompt so the handler clones and creates the lima instance 527 await opencode.sessions.prompt({ 528 sessionID: session.id, 529 text: "hello", 530 }); 531 532 const sessionDir = path.join(openpodRoot, session.id); 533 expect(await exists(sessionDir)).toBe(true); 534 535 // Wait for the prompt hook's async session.move() to land the session 536 // in the openpod directory. The create.before hook only wraps the 537 // command with `limactl shell` when cwd is inside openpodRoot. 538 for (let i = 0; i < 50; i++) { 539 const current = await opencode.sessions.get({ sessionID: session.id }); 540 if (current.location?.directory === sessionDir) break; 541 await new Promise((r) => setTimeout(r, 100)); 542 } 543 544 // Call shell.create — this triggers ctx.shell.hook("create.before"), 545 // which wraps the command with `limactl shell ... bash -c 'hostname'` 546 // so it executes inside the session's lima VM. 547 const shell = await opencode.shell.create({ 548 command: "hostname", 549 cwd: sessionDir, 550 }); 551 552 // Wait for the shell command to finish 553 for (let i = 0; i < 60; i++) { 554 const info = await opencode.shell.get({ 555 id: shell.data.id, 556 location: shell.location, 557 }); 558 if (info.data.status !== "running") break; 559 await new Promise((r) => setTimeout(r, 250)); 560 } 561 562 const output = await opencode.shell.output({ 563 id: shell.data.id, 564 location: shell.location, 565 }); 566 567 // hostname inside a lima VM is lima-<instance-name>, and lima replaces 568 // underscores with hyphens because hostnames can't contain underscores. 569 const expectedHost = session.id.replace(/_/g, "-"); 570 expect(output.data.output).toContain(expectedHost); 571 572 // Clean up 573 await cleanup(session.id, [sessionDir, tempDir, bareDir]); 574 }, 575 ); 576 });