file-operations.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import { constants as bufferConstants } from "buffer";
  2. import { appendFileSync, closeSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync, writeSync } from "fs";
  3. import { tmpdir } from "os";
  4. import { join } from "path";
  5. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  6. import { findMostRecentSession, loadEntriesFromFile, SessionManager } from "../../src/core/session-manager.ts";
  7. describe("loadEntriesFromFile", () => {
  8. let tempDir: string;
  9. beforeEach(() => {
  10. tempDir = join(tmpdir(), `session-test-${Date.now()}`);
  11. mkdirSync(tempDir, { recursive: true });
  12. });
  13. afterEach(() => {
  14. rmSync(tempDir, { recursive: true, force: true });
  15. });
  16. it("returns empty array for non-existent file", () => {
  17. const entries = loadEntriesFromFile(join(tempDir, "nonexistent.jsonl"));
  18. expect(entries).toEqual([]);
  19. });
  20. it("returns empty array for empty file", () => {
  21. const file = join(tempDir, "empty.jsonl");
  22. writeFileSync(file, "");
  23. expect(loadEntriesFromFile(file)).toEqual([]);
  24. });
  25. it("returns empty array for file without valid session header", () => {
  26. const file = join(tempDir, "no-header.jsonl");
  27. writeFileSync(file, '{"type":"message","id":"1"}\n');
  28. expect(loadEntriesFromFile(file)).toEqual([]);
  29. });
  30. it("returns empty array for malformed JSON", () => {
  31. const file = join(tempDir, "malformed.jsonl");
  32. writeFileSync(file, "not json\n");
  33. expect(loadEntriesFromFile(file)).toEqual([]);
  34. });
  35. it("loads valid session file", () => {
  36. const file = join(tempDir, "valid.jsonl");
  37. writeFileSync(
  38. file,
  39. '{"type":"session","id":"abc","timestamp":"2025-01-01T00:00:00Z","cwd":"/tmp"}\n' +
  40. '{"type":"message","id":"1","parentId":null,"timestamp":"2025-01-01T00:00:01Z","message":{"role":"user","content":"hi","timestamp":1}}\n',
  41. );
  42. const entries = loadEntriesFromFile(file);
  43. expect(entries).toHaveLength(2);
  44. expect(entries[0].type).toBe("session");
  45. expect(entries[1].type).toBe("message");
  46. });
  47. it("skips malformed lines but keeps valid ones", () => {
  48. const file = join(tempDir, "mixed.jsonl");
  49. writeFileSync(
  50. file,
  51. '{"type":"session","id":"abc","timestamp":"2025-01-01T00:00:00Z","cwd":"/tmp"}\n' +
  52. "not valid json\n" +
  53. '{"type":"message","id":"1","parentId":null,"timestamp":"2025-01-01T00:00:01Z","message":{"role":"user","content":"hi","timestamp":1}}\n',
  54. );
  55. const entries = loadEntriesFromFile(file);
  56. expect(entries).toHaveLength(2);
  57. });
  58. it("opens session files larger than Node's max string length", () => {
  59. const file = join(tempDir, "large.jsonl");
  60. writeFileSync(
  61. file,
  62. '{"type":"session","version":3,"id":"abc","timestamp":"2025-01-01T00:00:00Z","cwd":"/tmp"}\n',
  63. );
  64. const fd = openSync(file, "r+");
  65. try {
  66. const newline = Buffer.from("\n");
  67. const stride = 16 * 1024 * 1024;
  68. for (let offset = stride; offset <= bufferConstants.MAX_STRING_LENGTH + stride; offset += stride) {
  69. writeSync(fd, newline, 0, newline.length, offset);
  70. }
  71. } finally {
  72. closeSync(fd);
  73. }
  74. appendFileSync(
  75. file,
  76. '{"type":"message","id":"1","parentId":null,"timestamp":"2025-01-01T00:00:01Z","message":{"role":"user","content":"hi","timestamp":1}}\n',
  77. );
  78. const sessionManager = SessionManager.open(file, tempDir);
  79. expect(sessionManager.getSessionId()).toBe("abc");
  80. expect(sessionManager.getEntries()).toHaveLength(1);
  81. expect(sessionManager.buildSessionContext().messages).toEqual([{ role: "user", content: "hi", timestamp: 1 }]);
  82. });
  83. });
  84. describe("findMostRecentSession", () => {
  85. let tempDir: string;
  86. beforeEach(() => {
  87. tempDir = join(tmpdir(), `session-test-${Date.now()}`);
  88. mkdirSync(tempDir, { recursive: true });
  89. });
  90. afterEach(() => {
  91. rmSync(tempDir, { recursive: true, force: true });
  92. });
  93. it("returns null for empty directory", () => {
  94. expect(findMostRecentSession(tempDir)).toBeNull();
  95. });
  96. it("returns null for non-existent directory", () => {
  97. expect(findMostRecentSession(join(tempDir, "nonexistent"))).toBeNull();
  98. });
  99. it("ignores non-jsonl files", () => {
  100. writeFileSync(join(tempDir, "file.txt"), "hello");
  101. writeFileSync(join(tempDir, "file.json"), "{}");
  102. expect(findMostRecentSession(tempDir)).toBeNull();
  103. });
  104. it("ignores jsonl files without valid session header", () => {
  105. writeFileSync(join(tempDir, "invalid.jsonl"), '{"type":"message"}\n');
  106. expect(findMostRecentSession(tempDir)).toBeNull();
  107. });
  108. it("returns single valid session file", () => {
  109. const file = join(tempDir, "session.jsonl");
  110. writeFileSync(file, '{"type":"session","id":"abc","timestamp":"2025-01-01T00:00:00Z","cwd":"/tmp"}\n');
  111. expect(findMostRecentSession(tempDir)).toBe(file);
  112. });
  113. it("returns most recently modified session", async () => {
  114. const file1 = join(tempDir, "older.jsonl");
  115. const file2 = join(tempDir, "newer.jsonl");
  116. writeFileSync(file1, '{"type":"session","id":"old","timestamp":"2025-01-01T00:00:00Z","cwd":"/tmp"}\n');
  117. // Small delay to ensure different mtime
  118. await new Promise((r) => setTimeout(r, 10));
  119. writeFileSync(file2, '{"type":"session","id":"new","timestamp":"2025-01-01T00:00:00Z","cwd":"/tmp"}\n');
  120. expect(findMostRecentSession(tempDir)).toBe(file2);
  121. });
  122. it("skips invalid files and returns valid one", async () => {
  123. const invalid = join(tempDir, "invalid.jsonl");
  124. const valid = join(tempDir, "valid.jsonl");
  125. writeFileSync(invalid, '{"type":"not-session"}\n');
  126. await new Promise((r) => setTimeout(r, 10));
  127. writeFileSync(valid, '{"type":"session","id":"abc","timestamp":"2025-01-01T00:00:00Z","cwd":"/tmp"}\n');
  128. expect(findMostRecentSession(tempDir)).toBe(valid);
  129. });
  130. it("filters most recent session by cwd", async () => {
  131. const projectA = join(tempDir, "project-a");
  132. const projectB = join(tempDir, "project-b");
  133. const fileA = join(tempDir, "a.jsonl");
  134. const fileB = join(tempDir, "b.jsonl");
  135. writeFileSync(
  136. fileA,
  137. `${JSON.stringify({ type: "session", id: "a", timestamp: "2025-01-01T00:00:00Z", cwd: projectA })}\n`,
  138. );
  139. await new Promise((r) => setTimeout(r, 10));
  140. writeFileSync(
  141. fileB,
  142. `${JSON.stringify({ type: "session", id: "b", timestamp: "2025-01-01T00:00:00Z", cwd: projectB })}\n`,
  143. );
  144. expect(findMostRecentSession(tempDir, projectA)).toBe(fileA);
  145. expect(findMostRecentSession(tempDir, projectB)).toBe(fileB);
  146. });
  147. });
  148. describe("SessionManager custom flat session directory", () => {
  149. let tempDir: string;
  150. let projectA: string;
  151. let projectB: string;
  152. beforeEach(() => {
  153. tempDir = join(tmpdir(), `session-test-${Date.now()}`);
  154. projectA = join(tempDir, "project-a");
  155. projectB = join(tempDir, "project-b");
  156. mkdirSync(projectA, { recursive: true });
  157. mkdirSync(projectB, { recursive: true });
  158. });
  159. afterEach(() => {
  160. rmSync(tempDir, { recursive: true, force: true });
  161. });
  162. function createPersistedSession(cwd: string, label: string): string {
  163. const session = SessionManager.create(cwd, tempDir);
  164. session.appendMessage({ role: "user", content: label, timestamp: Date.now() });
  165. session.appendMessage({
  166. role: "assistant",
  167. content: [{ type: "text", text: `reply to ${label}` }],
  168. api: "anthropic-messages",
  169. provider: "anthropic",
  170. model: "test",
  171. usage: {
  172. input: 1,
  173. output: 1,
  174. cacheRead: 0,
  175. cacheWrite: 0,
  176. totalTokens: 2,
  177. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  178. },
  179. stopReason: "stop",
  180. timestamp: Date.now(),
  181. });
  182. const sessionFile = session.getSessionFile();
  183. if (!sessionFile) {
  184. throw new Error("Expected persisted session file");
  185. }
  186. return sessionFile;
  187. }
  188. it("scopes current-folder APIs by cwd while listing all flat sessions", async () => {
  189. const sessionA = createPersistedSession(projectA, "from A");
  190. await new Promise((r) => setTimeout(r, 10));
  191. const sessionB = createPersistedSession(projectB, "from B");
  192. const currentA = await SessionManager.list(projectA, tempDir);
  193. expect(currentA.map((session) => session.path)).toEqual([sessionA]);
  194. const all = await SessionManager.listAll(tempDir);
  195. expect(new Set(all.map((session) => session.path))).toEqual(new Set([sessionA, sessionB]));
  196. const continuedA = SessionManager.continueRecent(projectA, tempDir);
  197. expect(continuedA.getSessionFile()).toBe(sessionA);
  198. });
  199. });
  200. describe("SessionManager.setSessionFile with corrupted files", () => {
  201. let tempDir: string;
  202. beforeEach(() => {
  203. tempDir = join(tmpdir(), `session-test-${Date.now()}`);
  204. mkdirSync(tempDir, { recursive: true });
  205. });
  206. afterEach(() => {
  207. rmSync(tempDir, { recursive: true, force: true });
  208. });
  209. it("truncates and rewrites empty file with valid header", () => {
  210. const emptyFile = join(tempDir, "empty.jsonl");
  211. writeFileSync(emptyFile, "");
  212. const sm = SessionManager.open(emptyFile, tempDir);
  213. // Should have created a new session with valid header
  214. expect(sm.getSessionId()).toBeTruthy();
  215. expect(sm.getHeader()).toBeTruthy();
  216. expect(sm.getHeader()?.type).toBe("session");
  217. // File should now contain a valid header
  218. const content = readFileSync(emptyFile, "utf-8");
  219. const lines = content.trim().split("\n").filter(Boolean);
  220. expect(lines.length).toBe(1);
  221. const header = JSON.parse(lines[0]);
  222. expect(header.type).toBe("session");
  223. expect(header.id).toBe(sm.getSessionId());
  224. });
  225. it("truncates and rewrites file without valid header", () => {
  226. const noHeaderFile = join(tempDir, "no-header.jsonl");
  227. // File with messages but no session header (corrupted state)
  228. writeFileSync(
  229. noHeaderFile,
  230. '{"type":"message","id":"abc","parentId":"orphaned","timestamp":"2025-01-01T00:00:00Z","message":{"role":"assistant","content":"test"}}\n',
  231. );
  232. const sm = SessionManager.open(noHeaderFile, tempDir);
  233. // Should have created a new session with valid header
  234. expect(sm.getSessionId()).toBeTruthy();
  235. expect(sm.getHeader()).toBeTruthy();
  236. expect(sm.getHeader()?.type).toBe("session");
  237. // File should now contain only a valid header (old content truncated)
  238. const content = readFileSync(noHeaderFile, "utf-8");
  239. const lines = content.trim().split("\n").filter(Boolean);
  240. expect(lines.length).toBe(1);
  241. const header = JSON.parse(lines[0]);
  242. expect(header.type).toBe("session");
  243. expect(header.id).toBe(sm.getSessionId());
  244. });
  245. it("preserves explicit session file path when recovering from corrupted file", () => {
  246. const explicitPath = join(tempDir, "my-session.jsonl");
  247. writeFileSync(explicitPath, "");
  248. const sm = SessionManager.open(explicitPath, tempDir);
  249. // The session file path should be preserved
  250. expect(sm.getSessionFile()).toBe(explicitPath);
  251. });
  252. it("subsequent loads of recovered file work correctly", () => {
  253. const corruptedFile = join(tempDir, "corrupted.jsonl");
  254. writeFileSync(corruptedFile, "garbage content\n");
  255. // First open recovers the file
  256. const sm1 = SessionManager.open(corruptedFile, tempDir);
  257. const sessionId = sm1.getSessionId();
  258. // Second open should load the recovered file successfully
  259. const sm2 = SessionManager.open(corruptedFile, tempDir);
  260. expect(sm2.getSessionId()).toBe(sessionId);
  261. expect(sm2.getHeader()?.type).toBe("session");
  262. });
  263. });