session-selector-path-delete.test.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { setKeybindings } from "@earendil-works/pi-tui";
  5. import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
  6. import { KeybindingsManager } from "../src/core/keybindings.ts";
  7. import type { SessionInfo } from "../src/core/session-manager.ts";
  8. import { SessionSelectorComponent } from "../src/modes/interactive/components/session-selector.ts";
  9. import { initTheme } from "../src/modes/interactive/theme/theme.ts";
  10. type Deferred<T> = {
  11. promise: Promise<T>;
  12. resolve: (value: T) => void;
  13. reject: (err: unknown) => void;
  14. };
  15. function createDeferred<T>(): Deferred<T> {
  16. let resolve: (value: T) => void = () => {};
  17. let reject: (err: unknown) => void = () => {};
  18. const promise = new Promise<T>((res, rej) => {
  19. resolve = res;
  20. reject = rej;
  21. });
  22. return { promise, resolve, reject };
  23. }
  24. async function flushPromises(): Promise<void> {
  25. await new Promise<void>((resolve) => {
  26. setImmediate(resolve);
  27. });
  28. }
  29. function stripAnsi(text: string): string {
  30. return text.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "");
  31. }
  32. function makeSession(overrides: Partial<SessionInfo> & { id: string }): SessionInfo {
  33. return {
  34. path: overrides.path ?? `/tmp/${overrides.id}.jsonl`,
  35. id: overrides.id,
  36. cwd: overrides.cwd ?? "",
  37. name: overrides.name,
  38. parentSessionPath: overrides.parentSessionPath,
  39. created: overrides.created ?? new Date(0),
  40. modified: overrides.modified ?? new Date(0),
  41. messageCount: overrides.messageCount ?? 1,
  42. firstMessage: overrides.firstMessage ?? "hello",
  43. allMessagesText: overrides.allMessagesText ?? "hello",
  44. };
  45. }
  46. function createSymlinkedSessionPaths(): {
  47. baseDir: string;
  48. parentAliasA: string;
  49. parentAliasB: string;
  50. childAliasB: string;
  51. } {
  52. const baseDir = mkdtempSync(join(tmpdir(), "pi-session-selector-"));
  53. const realDir = join(baseDir, "real");
  54. const aliasADir = join(baseDir, "alias-a");
  55. const aliasBDir = join(baseDir, "alias-b");
  56. mkdirSync(realDir, { recursive: true });
  57. mkdirSync(aliasADir, { recursive: true });
  58. mkdirSync(aliasBDir, { recursive: true });
  59. const sharedDir = join(realDir, "sessions");
  60. mkdirSync(sharedDir, { recursive: true });
  61. const aliasASessions = join(aliasADir, "sessions");
  62. const aliasBSessions = join(aliasBDir, "sessions");
  63. symlinkSync(sharedDir, aliasASessions);
  64. symlinkSync(sharedDir, aliasBSessions);
  65. const parentRealPath = join(sharedDir, "parent.jsonl");
  66. const childRealPath = join(sharedDir, "child.jsonl");
  67. writeFileSync(parentRealPath, "parent\n");
  68. writeFileSync(childRealPath, "child\n");
  69. return {
  70. baseDir,
  71. parentAliasA: join(aliasASessions, "parent.jsonl"),
  72. parentAliasB: join(aliasBSessions, "parent.jsonl"),
  73. childAliasB: join(aliasBSessions, "child.jsonl"),
  74. };
  75. }
  76. const CTRL_D = "\x04";
  77. const CTRL_BACKSPACE = "\x1b[127;5u";
  78. describe("session selector path/delete interactions", () => {
  79. const keybindings = new KeybindingsManager();
  80. const tempDirs: string[] = [];
  81. afterEach(() => {
  82. for (const dir of tempDirs.splice(0)) {
  83. rmSync(dir, { recursive: true, force: true });
  84. }
  85. });
  86. beforeEach(() => {
  87. // Ensure test isolation: keybindings are a global singleton
  88. setKeybindings(new KeybindingsManager());
  89. });
  90. beforeAll(() => {
  91. // session selector uses the global theme instance
  92. initTheme("dark");
  93. });
  94. it("does not treat Ctrl+Backspace as delete when search query is non-empty", async () => {
  95. const sessions = [makeSession({ id: "a" }), makeSession({ id: "b" })];
  96. const selector = new SessionSelectorComponent(
  97. async () => sessions,
  98. async () => [],
  99. () => {},
  100. () => {},
  101. () => {},
  102. () => {},
  103. { keybindings },
  104. );
  105. await flushPromises();
  106. const list = selector.getSessionList();
  107. const confirmationChanges: Array<string | null> = [];
  108. list.onDeleteConfirmationChange = (path) => confirmationChanges.push(path);
  109. list.handleInput("a");
  110. list.handleInput(CTRL_BACKSPACE);
  111. expect(confirmationChanges).toEqual([]);
  112. });
  113. it("enters confirmation mode on Ctrl+D even with a non-empty search query", async () => {
  114. const sessions = [makeSession({ id: "a" }), makeSession({ id: "b" })];
  115. const selector = new SessionSelectorComponent(
  116. async () => sessions,
  117. async () => [],
  118. () => {},
  119. () => {},
  120. () => {},
  121. () => {},
  122. { keybindings },
  123. );
  124. await flushPromises();
  125. const list = selector.getSessionList();
  126. const confirmationChanges: Array<string | null> = [];
  127. list.onDeleteConfirmationChange = (path) => confirmationChanges.push(path);
  128. list.handleInput("a");
  129. list.handleInput(CTRL_D);
  130. expect(confirmationChanges).toEqual([sessions[0]!.path]);
  131. });
  132. it("enters confirmation mode on Ctrl+Backspace when search query is empty", async () => {
  133. const sessions = [makeSession({ id: "a" }), makeSession({ id: "b" })];
  134. const selector = new SessionSelectorComponent(
  135. async () => sessions,
  136. async () => [],
  137. () => {},
  138. () => {},
  139. () => {},
  140. () => {},
  141. { keybindings },
  142. );
  143. await flushPromises();
  144. const list = selector.getSessionList();
  145. const confirmationChanges: Array<string | null> = [];
  146. list.onDeleteConfirmationChange = (path) => confirmationChanges.push(path);
  147. let deletedPath: string | null = null;
  148. list.onDeleteSession = async (sessionPath) => {
  149. deletedPath = sessionPath;
  150. };
  151. list.handleInput(CTRL_BACKSPACE);
  152. expect(confirmationChanges).toEqual([sessions[0]!.path]);
  153. list.handleInput("\r");
  154. expect(confirmationChanges).toEqual([sessions[0]!.path, null]);
  155. expect(deletedPath).toBe(sessions[0]!.path);
  156. });
  157. it("does not switch scope back to All when All load resolves after toggling back to Current", async () => {
  158. const currentSessions = [makeSession({ id: "current" })];
  159. const allDeferred = createDeferred<SessionInfo[]>();
  160. let allLoadCalls = 0;
  161. const selector = new SessionSelectorComponent(
  162. async () => currentSessions,
  163. async () => {
  164. allLoadCalls++;
  165. return allDeferred.promise;
  166. },
  167. () => {},
  168. () => {},
  169. () => {},
  170. () => {},
  171. { keybindings },
  172. );
  173. await flushPromises();
  174. const list = selector.getSessionList();
  175. list.handleInput("\t"); // current -> all (starts async load)
  176. list.handleInput("\t"); // all -> current
  177. allDeferred.resolve([makeSession({ id: "all" })]);
  178. await flushPromises();
  179. expect(allLoadCalls).toBe(1);
  180. const output = selector.render(120).join("\n");
  181. expect(output).toContain("Resume Session (Current Folder)");
  182. expect(output).not.toContain("Resume Session (All)");
  183. });
  184. it("does not start redundant All loads when toggling scopes while All is already loading", async () => {
  185. const currentSessions = [makeSession({ id: "current" })];
  186. const allDeferred = createDeferred<SessionInfo[]>();
  187. let allLoadCalls = 0;
  188. const selector = new SessionSelectorComponent(
  189. async () => currentSessions,
  190. async () => {
  191. allLoadCalls++;
  192. return allDeferred.promise;
  193. },
  194. () => {},
  195. () => {},
  196. () => {},
  197. () => {},
  198. { keybindings },
  199. );
  200. await flushPromises();
  201. const list = selector.getSessionList();
  202. list.handleInput("\t"); // current -> all (starts async load)
  203. list.handleInput("\t"); // all -> current
  204. list.handleInput("\t"); // current -> all again while load pending
  205. expect(allLoadCalls).toBe(1);
  206. allDeferred.resolve([makeSession({ id: "all" })]);
  207. await flushPromises();
  208. });
  209. it("threads sessions when parent and child paths use different symlink aliases", async () => {
  210. const paths = createSymlinkedSessionPaths();
  211. tempDirs.push(paths.baseDir);
  212. const sessions = [
  213. makeSession({
  214. id: "parent",
  215. path: paths.parentAliasB,
  216. name: "Parent",
  217. modified: new Date("2026-01-01T00:00:00.000Z"),
  218. }),
  219. makeSession({
  220. id: "child",
  221. path: paths.childAliasB,
  222. parentSessionPath: paths.parentAliasA,
  223. name: "Child",
  224. modified: new Date("2025-12-31T00:00:00.000Z"),
  225. }),
  226. ];
  227. const selector = new SessionSelectorComponent(
  228. async () => sessions,
  229. async () => [],
  230. () => {},
  231. () => {},
  232. () => {},
  233. () => {},
  234. { keybindings },
  235. );
  236. await flushPromises();
  237. const output = stripAnsi(selector.render(120).join("\n"));
  238. expect(output).toContain("Parent");
  239. expect(output).toContain("└─ Child");
  240. });
  241. it("treats the current session as active across symlink aliases", async () => {
  242. const paths = createSymlinkedSessionPaths();
  243. tempDirs.push(paths.baseDir);
  244. const sessions = [makeSession({ id: "parent", path: paths.parentAliasB, name: "Parent" })];
  245. const selector = new SessionSelectorComponent(
  246. async () => sessions,
  247. async () => [],
  248. () => {},
  249. () => {},
  250. () => {},
  251. () => {},
  252. { keybindings },
  253. paths.parentAliasA,
  254. );
  255. await flushPromises();
  256. const list = selector.getSessionList();
  257. const confirmationChanges: Array<string | null> = [];
  258. let errorMessage: string | undefined;
  259. list.onDeleteConfirmationChange = (path) => confirmationChanges.push(path);
  260. list.onError = (message) => {
  261. errorMessage = message;
  262. };
  263. list.handleInput(CTRL_D);
  264. expect(confirmationChanges).toEqual([]);
  265. expect(errorMessage).toBe("Cannot delete the currently active session");
  266. });
  267. });