startup-session-name.test.ts 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import { spawn } from "node:child_process";
  2. import { mkdirSync, mkdtempSync, 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-startup-session-name-"));
  16. tempDirs.push(dir);
  17. return dir;
  18. }
  19. interface CliDirs {
  20. agentDir: string;
  21. projectDir: string;
  22. sessionFile: string;
  23. }
  24. interface CliResult {
  25. code: number | null;
  26. signal: NodeJS.Signals | null;
  27. stderr: string;
  28. }
  29. function createSessionFile(projectDir: string, sessionFile: string): void {
  30. const timestamp = new Date().toISOString();
  31. writeFileSync(
  32. sessionFile,
  33. `${JSON.stringify({ type: "session", version: 3, id: "existing-session", timestamp, cwd: projectDir })}\n${JSON.stringify(
  34. {
  35. type: "message",
  36. id: "assistant-1",
  37. parentId: null,
  38. timestamp,
  39. message: {
  40. role: "assistant",
  41. content: [{ type: "text", text: "hello" }],
  42. provider: "anthropic",
  43. model: "claude-sonnet-4-5",
  44. timestamp: Date.now(),
  45. },
  46. },
  47. )}\n`,
  48. );
  49. }
  50. function readSessionInfoNames(sessionFile: string): string[] {
  51. return readFileSync(sessionFile, "utf8")
  52. .trim()
  53. .split("\n")
  54. .map((line) => JSON.parse(line) as { type?: string; name?: string })
  55. .filter((entry) => entry.type === "session_info")
  56. .map((entry) => entry.name ?? "");
  57. }
  58. async function runCli(args: string[], dirs: CliDirs): Promise<CliResult> {
  59. let stderr = "";
  60. const child = spawn(process.execPath, [cliPath, ...args], {
  61. cwd: dirs.projectDir,
  62. env: {
  63. ...process.env,
  64. [ENV_AGENT_DIR]: dirs.agentDir,
  65. PI_OFFLINE: "1",
  66. TSX_TSCONFIG_PATH: resolve(__dirname, "../../../tsconfig.json"),
  67. },
  68. stdio: ["ignore", "ignore", "pipe"],
  69. });
  70. child.stderr.on("data", (chunk) => {
  71. stderr += chunk.toString();
  72. });
  73. return new Promise((resolvePromise, reject) => {
  74. const timeout = setTimeout(() => {
  75. child.kill("SIGKILL");
  76. }, 10_000);
  77. child.on("error", (error) => {
  78. clearTimeout(timeout);
  79. reject(error);
  80. });
  81. child.on("close", (code, signal) => {
  82. clearTimeout(timeout);
  83. resolvePromise({ code, signal, stderr });
  84. });
  85. });
  86. }
  87. function setup(): CliDirs {
  88. const tempRoot = createTempDir();
  89. const dirs = {
  90. agentDir: join(tempRoot, "agent"),
  91. projectDir: join(tempRoot, "project"),
  92. sessionFile: join(tempRoot, "session.jsonl"),
  93. };
  94. mkdirSync(dirs.agentDir, { recursive: true });
  95. mkdirSync(dirs.projectDir, { recursive: true });
  96. createSessionFile(dirs.projectDir, dirs.sessionFile);
  97. return dirs;
  98. }
  99. describe("startup session name", () => {
  100. it("sets --name on the selected session before runtime model validation", async () => {
  101. const dirs = setup();
  102. const result = await runCli(
  103. ["--session", dirs.sessionFile, "--name", " CLI Named Session ", "--model", "missing-model", "-p", "hi"],
  104. dirs,
  105. );
  106. expect(result.code).toBe(1);
  107. expect(result.signal).toBeNull();
  108. expect(readSessionInfoNames(dirs.sessionFile)).toEqual(["CLI Named Session"]);
  109. });
  110. it("rejects empty --name values without appending session metadata", async () => {
  111. const dirs = setup();
  112. const result = await runCli(
  113. ["--session", dirs.sessionFile, "--name", " ", "--model", "missing-model", "-p", "hi"],
  114. dirs,
  115. );
  116. expect(result.code).toBe(1);
  117. expect(result.signal).toBeNull();
  118. expect(result.stderr).toContain("--name requires a non-empty value");
  119. expect(readSessionInfoNames(dirs.sessionFile)).toEqual([]);
  120. });
  121. });