session-id-readonly.test.ts 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import { spawn } from "node:child_process";
  2. import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  3. import { tmpdir } from "node:os";
  4. import { join, resolve } from "node:path";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { ENV_AGENT_DIR } from "../src/config.ts";
  7. const cliPath = resolve(__dirname, "../src/cli.ts");
  8. const tempDirs: string[] = [];
  9. afterEach(() => {
  10. for (const dir of tempDirs.splice(0)) {
  11. rmSync(dir, { recursive: true, force: true });
  12. }
  13. });
  14. function createTempDir(): string {
  15. const dir = mkdtempSync(join(tmpdir(), "pi-session-id-readonly-"));
  16. tempDirs.push(dir);
  17. return dir;
  18. }
  19. function hasSessionWithId(root: string, sessionId: string): boolean {
  20. if (!existsSync(root)) return false;
  21. for (const entry of readdirSync(root, { withFileTypes: true })) {
  22. const path = join(root, entry.name);
  23. if (entry.isDirectory() && hasSessionWithId(path, sessionId)) return true;
  24. if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
  25. try {
  26. const firstLine = readFileSync(path, "utf8").split("\n", 1)[0];
  27. const header = JSON.parse(firstLine) as { type?: string; id?: string };
  28. if (header.type === "session" && header.id === sessionId) return true;
  29. } catch {
  30. // Ignore malformed session files.
  31. }
  32. }
  33. return false;
  34. }
  35. interface CliDirs {
  36. agentDir: string;
  37. projectDir: string;
  38. sessionDir: string;
  39. }
  40. async function runCli(
  41. args: string[] | ((dirs: CliDirs) => string[]),
  42. setup?: (dirs: CliDirs) => void,
  43. ): Promise<{ code: number | null; agentDir: string; stderr: string }> {
  44. const tempRoot = createTempDir();
  45. const dirs: CliDirs = {
  46. agentDir: join(tempRoot, "agent"),
  47. projectDir: join(tempRoot, "project"),
  48. sessionDir: join(tempRoot, "sessions"),
  49. };
  50. mkdirSync(dirs.agentDir, { recursive: true });
  51. mkdirSync(dirs.projectDir, { recursive: true });
  52. setup?.(dirs);
  53. const resolvedArgs = typeof args === "function" ? args(dirs) : args;
  54. let stderr = "";
  55. const code = await new Promise<number | null>((resolvePromise, reject) => {
  56. const child = spawn(process.execPath, [cliPath, ...resolvedArgs], {
  57. cwd: dirs.projectDir,
  58. env: {
  59. ...process.env,
  60. [ENV_AGENT_DIR]: dirs.agentDir,
  61. PI_OFFLINE: "1",
  62. TSX_TSCONFIG_PATH: resolve(__dirname, "../../../tsconfig.json"),
  63. },
  64. stdio: ["ignore", "ignore", "pipe"],
  65. });
  66. child.stderr.on("data", (chunk) => {
  67. stderr += chunk.toString();
  68. });
  69. child.on("error", reject);
  70. child.on("close", resolvePromise);
  71. });
  72. return { code, agentDir: dirs.agentDir, stderr };
  73. }
  74. function writeSession(sessionDir: string, cwd: string, id: string): void {
  75. writeFileSync(
  76. join(sessionDir, `${id}.jsonl`),
  77. `${JSON.stringify({ type: "session", version: 3, id, timestamp: new Date().toISOString(), cwd })}\n`,
  78. );
  79. }
  80. describe("--session-id read-only commands", () => {
  81. it("does not reserve a session for --help", async () => {
  82. const result = await runCli(["--session-id", "read-only-help", "--help"]);
  83. expect(result.code).toBe(0);
  84. expect(hasSessionWithId(join(result.agentDir, "sessions"), "read-only-help")).toBe(false);
  85. });
  86. it("does not reserve a session for --list-models", async () => {
  87. const result = await runCli(["--session-id", "read-only-models", "--list-models"]);
  88. expect(result.code).toBe(0);
  89. expect(hasSessionWithId(join(result.agentDir, "sessions"), "read-only-models")).toBe(false);
  90. });
  91. });
  92. describe("--session-id validation", () => {
  93. it("rejects ids invalid under SessionManager rules without stack traces", async () => {
  94. for (const id of ["-bad", "bad id"]) {
  95. const result = await runCli(["--session-id", id, "-p", "hi"]);
  96. expect(result.code).toBe(1);
  97. expect(result.stderr).toContain("Session id must be non-empty");
  98. expect(result.stderr).not.toContain("SessionManager.create");
  99. }
  100. });
  101. });